Best Mockito code snippet using org.mockito.Spy.open
Source:OpenFileTest.java
...34public class OpenFileTest {35 private CloudPath file;36 private CloudProvider provider;37 private CompletableAsynchronousFileChannel fileChannel;38 private OpenFile openFile;39 private RangeSet<Long> populatedRanges;40 private RangeMap<Long, CompletionStage<Void>> activeRequests;41 public static final int DEFAULT_READAHEAD_SIZE = 1024 * 1024 * 4; // 4 MiB42 @BeforeEach43 public void setup() throws IOException {44 this.file = Mockito.mock(CloudPath.class, "/path/to/file");45 this.provider = Mockito.mock(CloudProvider.class);46 this.fileChannel = Mockito.mock(CompletableAsynchronousFileChannel.class);47 this.populatedRanges = Mockito.spy(TreeRangeSet.create());48 this.activeRequests = Mockito.spy(TreeRangeMap.create());49 this.openFile = new OpenFile(file, fileChannel, provider, populatedRanges, activeRequests, Instant.EPOCH, DEFAULT_READAHEAD_SIZE);50 Mockito.when(fileChannel.size()).thenReturn(100l);51 Mockito.when(fileChannel.isOpen()).thenReturn(true);52 }53 @DisplayName("create new cached file")54 @ParameterizedTest(name = "with initial size={0}")55 @ValueSource(longs = {0l, 1l, 42l})56 public void testCreate(long size, @TempDir Path tmpDir) throws IOException {57 Path tmpFile = tmpDir.resolve("cache.file");58 try (var cachedFile = OpenFile.create(file, tmpFile, provider, size, DEFAULT_READAHEAD_SIZE)) {59 Assertions.assertNotNull(cachedFile);60 Assertions.assertEquals(size, cachedFile.getSize());61 }62 Assertions.assertTrue(Files.notExists(tmpFile));63 }64 @Test65 @DisplayName("test perstistTo(...)")66 public void testPersist(@TempDir Path tmpDir) throws IOException {67 Path tmpFile = tmpDir.resolve("cache.file");68 Path persistentFile = tmpDir.resolve("persistent.file");69 try (var cachedFile = OpenFile.create(file, tmpFile, provider, 0, DEFAULT_READAHEAD_SIZE)) {70 cachedFile.truncate(100l);71 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> cachedFile.persistTo(persistentFile).toCompletableFuture().get());72 }73 Assertions.assertTrue(Files.notExists(tmpFile));74 Assertions.assertTrue(Files.exists(persistentFile));75 Assertions.assertEquals(100, Files.size(persistentFile));76 }77 @Nested78 @DisplayName("write(...)")79 public class Write {80 @DisplayName("fail due to I/O error")81 @Test82 public void testWriteFailsWithException() {83 var e = new IOException("fail");84 CompletableFuture<Integer> failedFuture = CompletableFuture.failedFuture(e);85 var buf = Mockito.mock(Pointer.class);86 Mockito.when(fileChannel.writeFromPointer(buf, 1000l, 42l)).thenReturn(failedFuture);87 var futureResult = openFile.write(buf, 1000l, 42l);88 var thrown = Assertions.assertThrows(ExecutionException.class, () -> {89 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());90 });91 Assertions.assertEquals(e, thrown.getCause());92 }93 @DisplayName("successful write")94 @ParameterizedTest(name = "write(buf, 1000, {0})")95 @ValueSource(ints = {0, 100, 1023, 1024, 1025, 10_000})96 public void testWrite(int n) {97 Assumptions.assumeTrue(openFile.getSize() == 100l);98 var buf = Mockito.mock(Pointer.class);99 Mockito.when(fileChannel.writeFromPointer(buf, 1000l, n)).thenReturn(CompletableFuture.completedFuture(n));100 Assumptions.assumeTrue(openFile.getState() == OpenFile.State.UNMODIFIED);101 var futureResult = openFile.write(buf, 1000l, n);102 var result = Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());103 Assertions.assertEquals(n, result);104 Assertions.assertEquals(OpenFile.State.NEEDS_UPLOAD, openFile.getState());105 Mockito.verify(populatedRanges).add(Range.closedOpen(100l, 1000l)); // fils is grown from 100 to 1000106 Mockito.verify(populatedRanges).add(Range.closedOpen(1000l, 1000l + n)); // content of size n gets written starting at 1000107 }108 }109 @Nested110 @DisplayName("read(...)")111 public class Read {112 OpenFile fileSpy;113 @BeforeEach114 void setup() {115 fileSpy = Mockito.spy(openFile);116 Mockito.doReturn(CompletableFuture.completedFuture(null)).when(fileSpy).load(Mockito.anyLong(), Mockito.anyLong());117 }118 @DisplayName("no-op read (offset >= EOF)")119 @ParameterizedTest(name = "read(buf, {0}, 10)")120 @ValueSource(longs = {100l, 101l})121 public void testReadBeyondEof(long offset) throws IOException {122 Mockito.when(fileChannel.size()).thenReturn(100l);123 var buf = Mockito.mock(Pointer.class);124 var futureResult = fileSpy.read(buf, offset, 10);125 var result = Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());126 Assertions.assertEquals(0, result);127 Mockito.verify(fileSpy, Mockito.never()).load(Mockito.anyLong(), Mockito.anyLong());128 }129 @DisplayName("successful read")130 @ParameterizedTest(name = "read(buf, 100, {0})")131 @ValueSource(ints = {0, 100, 1023, 1024, 1025, 10_000})132 public void testReadSuccess(int readSize) throws IOException {133 long readOffset = 100;134 var buf = Mockito.mock(Pointer.class);135 Mockito.when(fileChannel.size()).thenReturn(100_000l);136 Mockito.when(fileChannel.readToPointer(buf, readOffset, readSize)).thenReturn(CompletableFuture.completedFuture(readSize));137 var futureResult = fileSpy.read(buf, readOffset, readSize);138 var result = Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());139 Assertions.assertEquals(readSize, result);140 Assertions.assertEquals(OpenFile.State.UNMODIFIED, openFile.getState());141 }142 @Test143 @DisplayName("fail due to I/O error in readToPointer()")144 public void testReadFailure() {145 var e = new IOException();146 CompletableFuture failure = CompletableFuture.failedFuture(e);147 Mockito.when(fileChannel.readToPointer(Mockito.any(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(failure);148 var futureResult = fileSpy.read(Mockito.mock(Pointer.class), 42, 1024);149 var thrown = Assertions.assertThrows(ExecutionException.class, () -> {150 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());151 });152 Assertions.assertEquals(e, thrown.getCause());153 Mockito.verify(fileSpy).load(42, 1024);154 }155 @Test156 @DisplayName("fail due to load() error")157 public void testLoadFailure() {158 var e = new Exception();159 Mockito.doReturn(CompletableFuture.failedFuture(e)).when(fileSpy).load(Mockito.anyLong(), Mockito.anyLong());160 var futureResult = fileSpy.read(Mockito.mock(Pointer.class), 42, 1024);161 var thrown = Assertions.assertThrows(ExecutionException.class, () -> {162 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());163 });164 Assertions.assertEquals(e, thrown.getCause());165 Mockito.verify(fileSpy).load(42, 1024);166 }167 }168 @Nested169 @DisplayName("completedRequest(...)")170 public class CompleteRequest {171 private CompletionStage<Void> req1 = Mockito.mock(CompletionStage.class);172 private CompletionStage<Void> req2 = Mockito.mock(CompletionStage.class);173 @BeforeEach174 public void setup() {175 activeRequests.put(Range.closedOpen(0l, 50l), req1);176 activeRequests.put(Range.closedOpen(50l, 100l), req2);177 Mockito.reset(activeRequests);178 }179 @Test180 @DisplayName("remove [0, 50) req1")181 public void testRemoveOnExactMatch() {182 openFile.completedRequest(Range.closedOpen(0l, 50l), req1);183 Mockito.verify(activeRequests).remove(Range.closedOpen(0l, 50l));184 }185 @Test186 @DisplayName("remove [0, 50) req2")187 public void testRemoveDifferentRequest() {188 openFile.completedRequest(Range.closedOpen(0l, 50l), req2);189 Mockito.verify(activeRequests, Mockito.never()).remove(Mockito.any());190 }191 @Test192 @DisplayName("remove [20, 80) req2")193 public void testRemoveRangeNotCurrentlyRequested() {194 openFile.completedRequest(Range.closedOpen(20l, 80l), req1);195 Mockito.verify(activeRequests, Mockito.never()).remove(Mockito.any());196 }197 @Test198 @DisplayName("remove [0, 50) req1 after making a broader request")199 public void testRemoveReplacedRange() {200 activeRequests.put(Range.closedOpen(0l, 150l), req2);201 Mockito.reset(activeRequests);202 openFile.completedRequest(Range.closedOpen(0l, 50l), req1);203 Mockito.verify(activeRequests, Mockito.never()).remove(Mockito.any());204 }205 }206 @Nested207 @DisplayName("load(...)")208 public class Load {209 OpenFile fileSpy;210 @BeforeEach211 public void setup() {212 this.fileSpy = Mockito.spy(openFile);213 Mockito.doReturn(CompletableFuture.completedFuture(null)).when(fileSpy).mergeData(Mockito.any(), Mockito.any());214 }215 @DisplayName("load 0 bytes")216 @ParameterizedTest(name = "region [{0}, ...]")217 @ValueSource(longs = {0l, 1l, 99l, 100l, 101l})218 public void testLoadZero(long offset) throws IOException {219 Mockito.when(fileChannel.size()).thenReturn(100l);220 var futureResult = fileSpy.load(offset, 0);221 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());222 Mockito.verify(fileSpy, Mockito.never()).mergeData(Mockito.any(), Mockito.any());223 Mockito.verify(activeRequests, Mockito.never()).put(Mockito.any(), Mockito.any());224 }225 @DisplayName("region behind at EOF (100)")226 @ParameterizedTest(name = "region [{0}, ...]")227 @ValueSource(longs = {100l, 101l})228 public void testLoadFailsAfterEof(long offset) throws IOException {229 Mockito.when(fileChannel.size()).thenReturn(100l);230 Assertions.assertThrows(IllegalArgumentException.class, () -> fileSpy.load(offset, 10));231 Mockito.verify(fileSpy, Mockito.never()).mergeData(Mockito.any(), Mockito.any());232 Mockito.verify(activeRequests, Mockito.never()).put(Mockito.any(), Mockito.any());233 }234 @Test235 @DisplayName("region [90, 110] till EOF (100)")236 public void testLoadToEof() throws IOException {237 var inputStream = Mockito.mock(InputStream.class);238 Mockito.when(fileChannel.size()).thenReturn(100l);239 Mockito.when(provider.read(Mockito.eq(file), Mockito.eq(90l), Mockito.anyLong(), Mockito.any())).thenReturn(CompletableFuture.completedFuture(inputStream));240 var futureResult = fileSpy.load(90l, 20l);241 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());242 Mockito.verify(fileSpy).mergeData(Mockito.argThat(r -> r.lowerEndpoint() == 90l && r.upperEndpoint() >= 100), Mockito.eq(inputStream));243 Mockito.verify(activeRequests).put(Mockito.eq(Range.closedOpen(90l, 100l)), Mockito.any());244 }245 @Test246 @DisplayName("region [50, 60] (miss)")247 public void testLoadNonExisting() {248 var inputStream = Mockito.mock(InputStream.class);249 Mockito.when(provider.read(Mockito.eq(file), Mockito.eq(50l), Mockito.anyLong(), Mockito.any())).thenReturn(CompletableFuture.completedFuture(inputStream));250 var futureResult = fileSpy.load(50l, 10l);251 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());252 Mockito.verify(fileSpy).mergeData(Mockito.argThat(r -> r.lowerEndpoint() == 50l && r.upperEndpoint() >= 60), Mockito.eq(inputStream));253 Mockito.verify(activeRequests).put(Mockito.eq(Range.closedOpen(50l, 100l)), Mockito.any());254 }255 @Test256 @DisplayName("region [50, 60] (fail exceptionally due to failed future)")257 public void testLoadFailsA() {258 var e = new CloudProviderException("fail.");259 Mockito.when(provider.read(Mockito.eq(file), Mockito.eq(50l), Mockito.anyLong(), Mockito.any())).thenReturn(CompletableFuture.failedFuture(e));260 var futureResult = fileSpy.load(50, 10);261 var thrown = Assertions.assertThrows(CloudProviderException.class, () -> {262 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().join());263 });264 Assertions.assertTrue(futureResult.toCompletableFuture().isCompletedExceptionally());265 Assertions.assertEquals(e, thrown);266 Mockito.verify(activeRequests).put(Mockito.eq(Range.closedOpen(50l, 100l)), Mockito.any());267 Mockito.verify(activeRequests, Mockito.atLeastOnce()).remove(Range.closedOpen(50l, 100l));268 }269 @Test270 @DisplayName("region [50, 60] (fail exceptionally due to failed merge)")271 public void testLoadFailsB() {272 var e = new IOException("fail.");273 Mockito.when(provider.read(Mockito.eq(file), Mockito.eq(50l), Mockito.anyLong(), Mockito.any())).thenReturn(CompletableFuture.completedFuture(Mockito.mock(InputStream.class)));274 Mockito.doReturn(CompletableFuture.failedFuture(e)).when(fileSpy).mergeData(Mockito.any(), Mockito.any());275 var futureResult = fileSpy.load(50, 10);276 var thrown = Assertions.assertThrows(ExecutionException.class, () -> {277 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());278 });279 Assertions.assertTrue(futureResult.toCompletableFuture().isCompletedExceptionally());280 Assertions.assertEquals(e, thrown.getCause());281 Mockito.verify(activeRequests).put(Mockito.eq(Range.closedOpen(50l, 100l)), Mockito.any());282 Mockito.verify(activeRequests, Mockito.atLeastOnce()).remove(Range.closedOpen(50l, 100l));283 }284 @Test285 @DisplayName("region [50, 50] (empty range)")286 public void testLoadEmptyRange() {287 var futureResult = fileSpy.load(50, 0);288 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());289 Mockito.verify(fileSpy, Mockito.never()).mergeData(Mockito.any(), Mockito.any());290 Mockito.verify(provider, Mockito.never()).read(Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.any());291 Mockito.verify(activeRequests, Mockito.never()).put(Mockito.any(), Mockito.any());292 }293 @Nested294 @DisplayName("When [50,60) is present...")295 public class WithPrepoluatedRanges {296 @BeforeEach297 public void setup() {298 populatedRanges.add(Range.closedOpen(50l, 60l));299 }300 @Test301 @DisplayName("region [50, 60] (hit)")302 public void testLoadCached() {303 var futureResult = fileSpy.load(50, 10);304 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());305 Mockito.verify(fileSpy, Mockito.never()).mergeData(Mockito.any(), Mockito.any());306 Mockito.verify(provider, Mockito.never()).read(Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.any());307 Mockito.verify(activeRequests, Mockito.never()).put(Mockito.any(), Mockito.any());308 }309 @Test310 @DisplayName("region [50, 70] (partial hit)")311 public void testLoadPartiallyCached() {312 var inputStream = Mockito.mock(InputStream.class);313 Mockito.when(provider.read(Mockito.eq(file), Mockito.eq(60l), Mockito.anyLong(), Mockito.any())).thenReturn(CompletableFuture.completedFuture(inputStream));314 var futureResult = fileSpy.load(50, 20);315 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> futureResult.toCompletableFuture().get());316 Mockito.verify(fileSpy).mergeData(Mockito.argThat(r -> r.lowerEndpoint() == 60l && r.upperEndpoint() >= 70), Mockito.eq(inputStream));317 Mockito.verify(activeRequests).put(Mockito.eq(Range.closedOpen(60l, 100l)), Mockito.any());318 Mockito.verify(activeRequests, Mockito.atLeastOnce()).remove(Range.closedOpen(60l, 100l));319 }320 }321 }322 @Nested323 @DisplayName("truncate(...)")324 public class Truncate {325 @BeforeEach326 public void setup() {327 Assumptions.assumeTrue(openFile.getSize() == 100l);328 Assumptions.assumeTrue(openFile.getState() == OpenFile.State.UNMODIFIED);329 }330 @DisplayName("shrinking (new size < 100)")331 @ParameterizedTest(name = "truncate({0})")332 @ValueSource(longs = {0l, 1l, 99l})333 public void testShrink(long size) throws IOException {334 openFile.truncate(size);335 Mockito.verify(fileChannel).truncate(size);336 Mockito.verify(fileChannel, Mockito.never()).write(Mockito.any(), Mockito.anyLong());337 Assertions.assertEquals(OpenFile.State.NEEDS_UPLOAD, openFile.getState());338 }339 @DisplayName("growing (new size > 100)")340 @ParameterizedTest(name = "truncate({0})")341 @ValueSource(longs = {101l, 150l})342 public void testGrow(long size) throws IOException {343 openFile.truncate(size);344 Mockito.verify(fileChannel, Mockito.never()).truncate(Mockito.anyLong());345 Mockito.verify(fileChannel).write(Mockito.argThat(b -> b.remaining() == 1), Mockito.eq(size - 1));346 Assertions.assertEquals(OpenFile.State.NEEDS_UPLOAD, openFile.getState());347 }348 @Test349 @DisplayName("no-op (new size == 100)")350 public void testNoop() throws IOException {351 openFile.truncate(100l);352 Mockito.verify(fileChannel, Mockito.never()).truncate(Mockito.anyLong());353 Mockito.verify(fileChannel, Mockito.never()).write(Mockito.any(), Mockito.anyLong());354 Assertions.assertEquals(OpenFile.State.UNMODIFIED, openFile.getState());355 }356 }357 @Nested358 @DisplayName("merge(...)")359 public class Merge {360 private InputStream in = Mockito.mock(InputStream.class);361 private OpenFile fileSpy;362 @BeforeEach363 public void setup() {364 var prePopulatedRanges = ImmutableRangeSet.of(Range.closedOpen(0l, 50l));365 populatedRanges = Mockito.spy(TreeRangeSet.create(prePopulatedRanges));366 openFile = new OpenFile(file, fileChannel, provider, populatedRanges, activeRequests, Instant.EPOCH, DEFAULT_READAHEAD_SIZE);367 this.fileSpy = Mockito.spy(openFile);368 }369 @Test370 @DisplayName("not intersecting populated ranges")371 public void testMergeFullRange() {372 var range = Range.closedOpen(100l, 120l);373 Assumptions.assumeFalse(populatedRanges.encloses(range));374 Mockito.when(fileChannel.transferFrom(Mockito.any(), Mockito.eq(100l), Mockito.eq(20l))).thenReturn(CompletableFuture.completedFuture(20l));375 Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> fileSpy.mergeData(range, in));376 Mockito.verify(populatedRanges).add(Range.closedOpen(100l, 120l));377 Assertions.assertTrue(populatedRanges.encloses(range));378 }379 @Test380 @DisplayName("partially populated (in between)")381 public void testMergePartiallyPopulatedRange1() throws IOException {...
Source:AuctionsSvcSpec_onAdaptv.java
...14import org.powermock.core.classloader.annotations.PowerMockIgnore;15import org.powermock.core.classloader.annotations.PrepareForTest;16import org.powermock.modules.junit4.PowerMockRunner;17import com.enremmeta.rtb.SharedSetUp;18import com.enremmeta.rtb.api.proto.openrtb.OpenRtbRequest;19import com.enremmeta.rtb.config.Lot49Config;20import com.enremmeta.rtb.constants.RtbConstants;21import com.enremmeta.rtb.proto.ExchangeAdapter;22import com.enremmeta.rtb.proto.adaptv.AdaptvAdapter;23import com.enremmeta.util.ServiceRunner;24@RunWith(PowerMockRunner.class)25@PrepareForTest({AuctionsSvc.class, ServiceRunner.class, AdaptvAdapter.class, UriInfo.class})26@PowerMockIgnore({"javax.crypto.*", "javax.management.*"})27public class AuctionsSvcSpec_onAdaptv {28 // should process request from Ad Exchange29 private ServiceRunner serviceRunnerSimpleMock;30 private AuctionsSvc svc;31 AdaptvAdapter adaptvAdapterMock;32 @Before33 public void setUp() throws Exception {34 serviceRunnerSimpleMock = Mockito.mock(ServiceRunner.class, Mockito.CALLS_REAL_METHODS);35 Lot49Config configMock = Mockito.mock(Lot49Config.class);36 PowerMockito.mockStatic(ServiceRunner.class);37 Mockito.when(ServiceRunner.getInstance()).thenReturn(serviceRunnerSimpleMock);38 Mockito.when(serviceRunnerSimpleMock.getConfig()).thenReturn(configMock);39 svc = new AuctionsSvc();40 PowerMockito.mockStatic(AuctionsSvc.class);41 PowerMockito.doNothing().when(AuctionsSvc.class);42 AuctionsSvc.onBidRequestDelegate(any(JerseySvc.class), anyString(),43 any(ExchangeAdapter.class), any(AsyncResponse.class),44 any(OpenRtbRequest.class), anyString(), any(HttpServletRequest.class),45 anyString());46 }47 @Test48 public void positiveFlow_shouldConfiureAdapterAndCallOnBidRequestDelegate() throws Exception {49 OpenRtbRequest req = new OpenRtbRequest();50 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);51 Mockito.when(adaptvAdapterMock.convertRequest(any(OpenRtbRequest.class)))52 .thenReturn(new OpenRtbRequest());53 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterMock);54 svc.onAdaptv(Mockito.mock(AsyncResponse.class), Mockito.mock(UriInfo.class), req, "xff",55 Mockito.mock(HttpServletRequest.class), "xrip", "debug");56 // verify adapter constructor call57 PowerMockito.verifyNew(AdaptvAdapter.class).withNoArguments();58 // verify ADX adapter call to convertRequest59 Mockito.verify(adaptvAdapterMock, times(1)).convertRequest(any(OpenRtbRequest.class));60 PowerMockito.verifyStatic(Mockito.times(1));61 AuctionsSvc.onBidRequestDelegate(any(JerseySvc.class), anyString(),62 any(ExchangeAdapter.class), any(AsyncResponse.class),63 any(OpenRtbRequest.class), anyString(), any(HttpServletRequest.class),64 anyString());65 }66 @Test67 public void negativeFlow_canNotSetOpenRtbRequestFromEmptyQuery() throws Exception {68 OpenRtbRequest req = new OpenRtbRequest();69 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);70 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterMock);71 svc.onAdaptv(Mockito.mock(AsyncResponse.class), PowerMockito.mock(UriInfo.class), req,72 "xff", Mockito.mock(HttpServletRequest.class), "xrip", "debug");73 // verify adapter constructor call74 PowerMockito.verifyNew(AdaptvAdapter.class).withNoArguments();75 // onBidRequestDelegate called even on null query?76 PowerMockito.verifyStatic(Mockito.times(1));77 AuctionsSvc.onBidRequestDelegate(any(JerseySvc.class), anyString(),78 any(ExchangeAdapter.class), any(AsyncResponse.class),79 any(OpenRtbRequest.class), anyString(), any(HttpServletRequest.class),80 anyString());81 // TODO:82 // refactoring idea: add exception throw for adaptvAdapter.convertRequest83 }84 @SuppressWarnings("serial")85 @Test86 public void positiveFlow_setOpenRtbRequestAuctionId() throws Exception {87 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);88 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);89 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);90 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))91 .thenCallRealMethod();92 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();93 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()94 .thenReturn(openRtbRequestMarker);95 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);96 OpenRtbRequest req = new OpenRtbRequest();97 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",98 Mockito.mock(HttpServletRequest.class), "xrip", "debug");99 assertEquals("AUCTION_ID", openRtbRequestMarker.getId());100 }101 @SuppressWarnings("serial")102 @Test103 public void positiveFlow_setOpenRtbRequestDevice() throws Exception {104 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);105 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);106 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);107 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))108 .thenCallRealMethod();109 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();110 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()111 .thenReturn(openRtbRequestMarker);112 OpenRtbRequest req = new OpenRtbRequest();113 svc.onAdaptv(Mockito.mock(AsyncResponse.class), Mockito.mock(UriInfo.class), req, "xff",114 Mockito.mock(HttpServletRequest.class), "xrip", "debug");115 assertEquals(SharedSetUp.IP_MARKER, openRtbRequestMarker.getDevice().getIp());116 assertEquals("TEST_UA_CHROME", openRtbRequestMarker.getDevice().getUa());117 assertEquals("TEST_LANG_ES", openRtbRequestMarker.getDevice().getLanguage());118 }119 @SuppressWarnings("serial")120 @Test121 public void positiveFlow_setOpenRtbRequestSite() throws Exception {122 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);123 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);124 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);125 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))126 .thenCallRealMethod();127 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();128 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()129 .thenReturn(openRtbRequestMarker);130 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);131 OpenRtbRequest req = new OpenRtbRequest();132 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",133 Mockito.mock(HttpServletRequest.class), "xrip", "debug");134 assertEquals("TEST_DOMAIN", openRtbRequestMarker.getSite().getDomain());135 assertEquals("TEST_URL", openRtbRequestMarker.getSite().getRef());136 assertEquals("TEST_URL", openRtbRequestMarker.getSite().getPage());137 assertEquals("TEST_PLACEMENT_NAME", openRtbRequestMarker.getSite().getName());138 }139 @SuppressWarnings("serial")140 @Test141 public void positiveFlow_setOpenRtbRequestApp() throws Exception {142 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);143 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);144 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);145 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))146 .thenCallRealMethod();147 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();148 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()149 .thenReturn(openRtbRequestMarker);150 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);151 OpenRtbRequest req = new OpenRtbRequest();152 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",153 Mockito.mock(HttpServletRequest.class), "xrip", "debug");154 assertEquals("TEST_APP_NAME", openRtbRequestMarker.getApp().getName());155 }156 @SuppressWarnings("serial")157 @Test158 public void positiveFlow_setOpenRtbRequestImpression() throws Exception {159 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);160 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);161 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);162 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))163 .thenCallRealMethod();164 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();165 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()166 .thenReturn(openRtbRequestMarker);167 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);168 OpenRtbRequest req = new OpenRtbRequest();169 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",170 Mockito.mock(HttpServletRequest.class), "xrip", "debug");171 assertEquals("TEST_IMP_ID", openRtbRequestMarker.getImp().get(0).getId());172 }173 @SuppressWarnings("serial")174 @Test175 public void positiveFlow_setOpenRtbRequestVideoFormats() throws Exception {176 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);177 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);178 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);179 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))180 .thenCallRealMethod();181 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();182 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()183 .thenReturn(openRtbRequestMarker);184 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);185 OpenRtbRequest req = new OpenRtbRequest();186 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",187 Mockito.mock(HttpServletRequest.class), "xrip", "debug");188 assertEquals("video/x-flv",189 openRtbRequestMarker.getImp().get(0).getVideo().getMimes().get(0));190 assertEquals("video/mp4",191 openRtbRequestMarker.getImp().get(0).getVideo().getMimes().get(1));192 assertEquals("video/ogg",193 openRtbRequestMarker.getImp().get(0).getVideo().getMimes().get(2));194 }195 @SuppressWarnings("serial")196 @Test197 public void positiveFlow_setOpenRtbRequestPlayackMethod() throws Exception {198 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);199 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);200 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);201 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))202 .thenCallRealMethod();203 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();204 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()205 .thenReturn(openRtbRequestMarker);206 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);207 OpenRtbRequest req = new OpenRtbRequest();208 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",209 Mockito.mock(HttpServletRequest.class), "xrip", "debug");210 assertEquals(2, openRtbRequestMarker.getImp().get(0).getVideo().getPlaybackmethod().get(0)211 .intValue());212 }213 @SuppressWarnings("serial")214 @Test215 public void positiveFlow_setOpenRtbRequestOtherVideoSettings() throws Exception {216 adaptvAdapterMock = PowerMockito.mock(AdaptvAdapter.class);217 AdaptvAdapter adaptvAdapterSpy = PowerMockito.spy(adaptvAdapterMock);218 PowerMockito.whenNew(AdaptvAdapter.class).withNoArguments().thenReturn(adaptvAdapterSpy);219 PowerMockito.when(adaptvAdapterSpy.convertRequest(any(OpenRtbRequest.class)))220 .thenCallRealMethod();221 OpenRtbRequest openRtbRequestMarker = new OpenRtbRequest();222 PowerMockito.whenNew(OpenRtbRequest.class).withNoArguments()223 .thenReturn(openRtbRequestMarker);224 UriInfo uriInfoMock = PowerMockito.mock(UriInfo.class);225 OpenRtbRequest req = new OpenRtbRequest();226 svc.onAdaptv(Mockito.mock(AsyncResponse.class), uriInfoMock, req, "xff",227 Mockito.mock(HttpServletRequest.class), "xrip", "debug");228 assertEquals(1, openRtbRequestMarker.getImp().get(0).getVideo().getMinduration());229 assertEquals(10, openRtbRequestMarker.getImp().get(0).getVideo().getMaxduration());230 assertEquals(350, openRtbRequestMarker.getImp().get(0).getVideo().getH());231 assertEquals(350, openRtbRequestMarker.getImp().get(0).getVideo().getW());232 assertEquals(RtbConstants.API_VPAID_1,233 openRtbRequestMarker.getImp().get(0).getVideo().getApi().get(0).intValue());234 assertEquals(RtbConstants.API_VPAID_2,235 openRtbRequestMarker.getImp().get(0).getVideo().getApi().get(1).intValue());236 }237}...
Source:BidAskHandlerSimpleTest.java
1package org.assassin.jr.attabot.service.scheduler;2import static org.mockito.Mockito.doReturn;3import static org.mockito.Mockito.spy;4import static org.mockito.Mockito.times;5import static org.mockito.Mockito.verify;6import java.util.ArrayList;7import java.util.List;8import org.assassin.jr.attabot.config.CurrencySetting;9import org.assassin.jr.attabot.config.PredictType;10import org.assassin.jr.attabot.pojo.exchange.IOrder;11import org.assassin.jr.attabot.pojo.exchange.ITicker;12import org.assassin.jr.attabot.pojo.exchange.bittrex.BittrexOpenOrder;13import org.assassin.jr.attabot.pojo.exchange.bittrex.BittrexOrderHistory;14import org.assassin.jr.attabot.pojo.exchange.bittrex.BittrexTicker;15import org.assassin.jr.attabot.service.exchange.ExchangeAccountService;16import org.assassin.jr.attabot.service.exchange.ExchangeMarketService;17import org.assassin.jr.attabot.service.exchange.ExchangePublicService;18import org.assassin.jr.attabot.service.exchange.ExchangeServiceHandler;19import org.assassin.jr.attabot.service.exchange.bittrex.BittrexAccountService;20import org.assassin.jr.attabot.service.exchange.bittrex.BittrexExchangeService;21import org.assassin.jr.attabot.service.exchange.bittrex.BittrexMaketService;22import org.assassin.jr.attabot.service.exchange.bittrex.BittrexPublicService;23import org.assassin.jr.attabot.service.management.OrdersManagement;24import org.assassin.jr.attabot.service.predictor.PredictorFactoryCache;25import org.assassin.jr.attabot.utility.AttaConstant;26import org.junit.Test;27import org.mockito.Mockito;28public class BidAskHandlerSimpleTest {29 @Test30 public void testBidFirstTime() throws Exception {31 System.out.println("==================================================================");32 System.out.println("testBidFirstTime");33 BidAskHandlerSimple handleSimpleSpy = spy(new BidAskHandlerSimple());34 CurrencySetting currency = getStandardCurrencySetting();35 ExchangeServiceHandler exchangeServiceSpy = getStandardMockExchangeService(currency);36 37 handleSimpleSpy.handleOrder(currency, exchangeServiceSpy, PredictorFactoryCache.getPredictor(PredictType.OVERLAP));38 ITicker ticker = exchangeServiceSpy.getPublicService().getTicker(currency.getMarket());39 verify(exchangeServiceSpy.getMarketService(), times(0)).sellLimit(Mockito.anyString(), Mockito.anyDouble(), Mockito.anyDouble());40 verify(exchangeServiceSpy.getMarketService(), times(1)).buyLimit(currency.getMarket(), currency.getBudget() / ticker.getBid(), ticker.getBid());41 System.out.println("==================================================================");42 }43 @Test44 public void testBidSecondTime() throws Exception {45 System.out.println("==================================================================");46 System.out.println("testBidSecondTime");47 // check time 148 BidAskHandlerSimple handleSimpleSpy = spy(new BidAskHandlerSimple());49 CurrencySetting currency = getStandardCurrencySetting();50 ExchangeServiceHandler exchangeServiceSpy = getStandardMockExchangeService(currency);51 //handleSimpleSpy.handleOrder(currency, exchangeServiceSpy, new ExchangePredictorWrapper(PredictType.OVERLAP, spy(new PredictorOverlapBid()), spy(new PredictorOverlapAsk())));52 ITicker ticker = exchangeServiceSpy.getPublicService().getTicker(currency.getMarket());53 verify(exchangeServiceSpy.getMarketService(), times(0)).sellLimit(Mockito.anyString(), Mockito.anyDouble(), Mockito.anyDouble());54 verify(exchangeServiceSpy.getMarketService(), times(1)).buyLimit(currency.getMarket(), currency.getBudget() / ticker.getBid(), ticker.getBid());55 // check time 256 List<IOrder> lstOpenOrder = new ArrayList<>();57 lstOpenOrder.add(new BittrexOpenOrder(OrdersManagement.getInstance().getOrder(currency.getId()).getUuid()));58 Mockito.when(exchangeServiceSpy.getMarketService().getOpenOrders(currency.getMarket())).thenReturn(lstOpenOrder);59 handleSimpleSpy.handleOrder(currency, exchangeServiceSpy, PredictorFactoryCache.getPredictor(PredictType.OVERLAP));60 verify(exchangeServiceSpy.getMarketService(), times(0)).sellLimit(Mockito.anyString(), Mockito.anyDouble(), Mockito.anyDouble());61 verify(exchangeServiceSpy.getMarketService(), times(1)).buyLimit(Mockito.anyString(), Mockito.anyDouble(), Mockito.anyDouble());62 System.out.println("==================================================================");63 }64 @Test65 public void testAskFirstTime() throws Exception {66 System.out.println("==================================================================");67 System.out.println("testAskFirstTime");68 // bid69 testBidFirstTime();70 // ask71 BidAskHandlerSimple handleSimpleSpy = spy(new BidAskHandlerSimple());72 CurrencySetting currency = getStandardCurrencySetting();73 ExchangeServiceHandler exchangeServiceSpy = getStandardMockExchangeService(currency);74 ITicker ticker = exchangeServiceSpy.getPublicService().getTicker(currency.getMarket());75 List<IOrder> lstOrderHistory = new ArrayList<>();76 BittrexOrderHistory orderHistory = new BittrexOrderHistory(OrdersManagement.getInstance().getOrder(currency.getId()).getUuid());77 orderHistory.setPrice(ticker.getBid());78 orderHistory.setQuantity(currency.getBudget() / ticker.getBid());79 orderHistory.setOrderType(AttaConstant.LIMIT_BUY);80 lstOrderHistory.add(orderHistory);81 Mockito.when(exchangeServiceSpy.getAccountService().getOrderHistory(currency.getMarket())).thenReturn(lstOrderHistory);82 handleSimpleSpy.handleOrder(currency, exchangeServiceSpy, PredictorFactoryCache.getPredictor(PredictType.OVERLAP));83 double sellPrice = orderHistory.getPrice() + orderHistory.getPrice() * currency.getProfitRate();84 verify(exchangeServiceSpy.getMarketService(), times(0)).buyLimit(Mockito.anyString(), Mockito.anyDouble(), Mockito.anyDouble());85 verify(exchangeServiceSpy.getMarketService(), times(1)).sellLimit(currency.getMarket(), orderHistory.getQuantity(), sellPrice);86 System.out.println("==================================================================");87 }88 private CurrencySetting getStandardCurrencySetting() throws Exception {89 return new CurrencySetting("BETH-1", "BETH", 0.01f, 0.5f, 0.25f, true, 0.00000867);90 }91 private ExchangeServiceHandler getStandardMockExchangeService(CurrencySetting currencySetting) throws Exception {92 String apiKeyTest = "api-key-123";93 String apiKeySerectTest = "api-key-serect-123";94 String buyUuid = "uuid-buy-key-12345";95 ExchangePublicService publicServiceSpy = spy(new BittrexPublicService(apiKeyTest, apiKeySerectTest));96 BittrexTicker ticker = new BittrexTicker(0.000535f, 0.0005f, 0.00051f);97 doReturn(ticker).when(publicServiceSpy).getTicker(currencySetting.getMarket());98 ExchangeMarketService marketServiceSpy = spy(new BittrexMaketService(apiKeyTest, apiKeySerectTest));99 List<BittrexOpenOrder> lstOpenOrder = new ArrayList<BittrexOpenOrder>();100 doReturn(lstOpenOrder).when(marketServiceSpy).getOpenOrders(currencySetting.getMarket());101 Mockito.when((marketServiceSpy.buyLimit(currencySetting.getMarket(), currencySetting.getBudget() / ticker.getBid(), ticker.getBid()))).thenReturn(buyUuid);102 ExchangeAccountService accountServiceSpy = spy(new BittrexAccountService(apiKeyTest, apiKeySerectTest));103 List<BittrexOrderHistory> lstOrderHistory = new ArrayList<>();104 doReturn(lstOrderHistory).when(accountServiceSpy).getOrderHistory(currencySetting.getMarket());105 ExchangeServiceHandler exchangeServiceSpy = spy(new BittrexExchangeService(apiKeyTest, apiKeySerectTest));106 doReturn(marketServiceSpy).when(exchangeServiceSpy).getMarketService();107 doReturn(accountServiceSpy).when(exchangeServiceSpy).getAccountService();108 doReturn(publicServiceSpy).when(exchangeServiceSpy).getPublicService();109 return exchangeServiceSpy;110 }111}...
Source:LoginInteractorTest.java
...23 private BaseLoginContract.Presenter presenter;24 @Mock25 private BaseLoginContract.View view;26 @Mock27 private Context opensrpContext;28 @Mock29 private AllSharedPreferences sharedPreferences;30 @Mock31 private UserService userService;32 @Before33 public void setUp() {34 MockitoAnnotations.initMocks(this);35 interactor = new LoginInteractor(presenter);36 }37 @Test38 public void testOnDestroyShouldNotResetThePresenterIfIsChangingConfigurationChangeIsTrue() {39 BaseLoginContract.Presenter presenter = Whitebox.getInternalState(interactor, FIELD_LOGIN_PRESENTER);40 Assert.assertNotNull(presenter);41 interactor.onDestroy(true);//configuration change42 presenter = Whitebox.getInternalState(interactor, FIELD_LOGIN_PRESENTER);43 Assert.assertNotNull(presenter);44 }45 @Test46 public void testOnDestroyShouldResetThePresenterIfIsChangingConfigurationChangeIsFalse() {47 BaseLoginContract.Presenter presenter = Whitebox.getInternalState(interactor, FIELD_LOGIN_PRESENTER);48 Assert.assertNotNull(presenter);49 interactor.onDestroy(false);//Not configuration change50 presenter = Whitebox.getInternalState(interactor, FIELD_LOGIN_PRESENTER);51 Assert.assertNull(presenter);52 }53 @Test54 public void testGetApplicationContextShouldInvokeGetApplicationContextOfLoginView() {55 LoginInteractor interactor = new LoginInteractor(presenter);56 Mockito.doReturn(view).when(presenter).getLoginView();57 interactor.getApplicationContext();58 Mockito.verify(view, Mockito.times(1)).getActivityContext();59 }60 @Test61 public void testGetAllSharedPreferencesShouldReturnCorrectSharedPreferences() {62 LoginPresenter presenter = new LoginPresenter(view);63 LoginPresenter presenterSpy = Mockito.spy(presenter);64 LoginInteractor interactor = new LoginInteractor(presenterSpy);65 LoginInteractor spyInteractor = Mockito.spy(interactor);66 Mockito.doReturn(opensrpContext).when(presenterSpy).getOpenSRPContext();67 Mockito.doReturn(sharedPreferences).when(opensrpContext).allSharedPreferences();68 spyInteractor.getSharedPreferences();69 Mockito.verify(presenterSpy, Mockito.times(1)).getOpenSRPContext();70 Mockito.verify(opensrpContext, Mockito.times(1)).allSharedPreferences();71 Assert.assertEquals(sharedPreferences, spyInteractor.getSharedPreferences());72 }73 @Test74 public void testGetLoginViewShouldInvokePresenterGetLoginViewMethod() {75 LoginPresenter presenter = new LoginPresenter(view);76 LoginPresenter presenterSpy = Mockito.spy(presenter);77 LoginInteractor interactor = new LoginInteractor(presenterSpy);78 LoginInteractor spyInteractor = Mockito.spy(interactor);79 spyInteractor.getLoginView();80 Mockito.verify(presenterSpy, Mockito.times(1)).getLoginView();81 Assert.assertTrue(presenterSpy.getLoginView() instanceof BaseLoginContract.View);82 }83 @Test84 public void testGetUserServiceShouldInvokeUserServiceMethodFromOpensrpContext() {85 LoginPresenter presenter = new LoginPresenter(view);86 LoginPresenter presenterSpy = Mockito.spy(presenter);87 LoginInteractor interactor = new LoginInteractor(presenterSpy);88 LoginInteractor spyInteractor = Mockito.spy(interactor);89 Mockito.doReturn(opensrpContext).when(presenterSpy).getOpenSRPContext();90 Mockito.doReturn(userService).when(opensrpContext).userService();91 spyInteractor.getUserService();92 Mockito.verify(presenterSpy, Mockito.times(1)).getOpenSRPContext();93 Mockito.verify(opensrpContext, Mockito.times(1)).userService();94 Assert.assertEquals(userService, spyInteractor.getUserService());95 }96 @Test97 public void testLoginShouldInvokeLoginWithLocalFlagWithCorrectParameters() {98 LoginPresenter presenter = new LoginPresenter(view);99 LoginPresenter presenterSpy = Mockito.spy(presenter);100 LoginInteractor interactor = new LoginInteractor(presenterSpy);101 LoginInteractor spyInteractor = Mockito.spy(interactor);102 spyInteractor.login(new WeakReference<>(view), DUMMY_USERNAME, DUMMY_PASSWORD.toCharArray());103 Mockito.verify(spyInteractor, Mockito.times(1)).loginWithLocalFlag(Mockito.any(WeakReference.class), Mockito.eq(false), Mockito.eq(DUMMY_USERNAME), Mockito.eq(DUMMY_PASSWORD.toCharArray()));104 }105 @Test106 public void testLoginWithFetchForceRemoteLoginTrueShouldInvokeLoginWithLocalFlagWithCorrectParameters() {107 LoginPresenter presenter = new LoginPresenter(view);...
Source:HSQLBookKeeperTest.java
...91 }92 @Test93 public void testWipe() throws SQLException {94 HSQLBookKeeper spyKeeper = spy(keeper);95 when(persistenceStore.openConnection()).thenReturn(connection);96 when(connection.createStatement()).thenReturn(statement);97 when(d1.getSequence()).thenReturn(Sequence.valueOf(1));98 when(statement.executeUpdate("DELETE FROM dbName WHERE SEQUENCE_ID=1;")).thenReturn(1);99 when(statement.executeUpdate("COMMIT;")).thenReturn(1);100 101 spyKeeper.wipe(d1);102 103 verify(statement).executeUpdate("DELETE FROM dbName WHERE SEQUENCE_ID=1;");104 verify(statement).executeUpdate("COMMIT;");105 }106 107 @Test(expected=RuntimeException.class)108 public void testWipe_throwsSQLException() throws SQLException {109 HSQLBookKeeper spyKeeper = spy(keeper);110 when(d1.getSequence()).thenReturn(Sequence.valueOf(1));111 when(persistenceStore.openConnection()).thenReturn(connection);112 when(connection.createStatement()).thenThrow(new SQLException());113 114 spyKeeper.wipe(d1);115 }116 @Test117 public void testWipeAll() throws SQLException {118 HSQLBookKeeper spyKeeper = spy(keeper);119 when(persistenceStore.openConnection()).thenReturn(connection);120 when(connection.createStatement()).thenReturn(statement);121 when(statement.executeUpdate("DELETE FROM dbName;")).thenReturn(1);122 when(statement.executeUpdate("COMMIT;")).thenReturn(1);123 124 spyKeeper.wipeAll();125 126 verify(statement).executeUpdate("DELETE FROM dbName;");127 verify(statement).executeUpdate("COMMIT;");128 }129 130 @Test(expected=RuntimeException.class)131 public void testWipeAll_throwsSQLException() throws SQLException {132 HSQLBookKeeper spyKeeper = spy(keeper);133 when(persistenceStore.openConnection()).thenReturn(connection);134 when(connection.createStatement()).thenThrow(new SQLException());135 136 spyKeeper.wipeAll();137 }138}...
Source:BlitzortungLightningSourceTest.java
...33 private BlitzortungLightningSource spySource;34 private BlitzortungLightningSource.WebSocketSubscriber spySubscriber;35 @BeforeMethod36 public void setUp() throws Exception {37 MockitoAnnotations.openMocks(this).close();38 spySource = Mockito.spy(new BlitzortungLightningSource(39 "ws://%s.com:%s", Arrays.asList("foo", "bar"),40 8080, 100, mockWebSocketFactory));41 spySubscriber = Mockito.spy(spySource.new WebSocketSubscriber(42 new URI("ws://foo.com"), mockInstantSupplier, mockGeoEventTranslator));43 }44 @Test45 public void testStart() {46 Mockito.doNothing().when(spySource).submit(Mockito.any());47 Mockito.doNothing().when(spySource).connect(Mockito.any());48 spySource.start();49 Mockito.verify(spySource).submit(captorRunnable.capture());50 Runnable function = captorRunnable.getValue();51 function.run();...
Source:RestaurantTest.java
...1415class RestaurantTest {16 Restaurant restaurant;17 public void addMenuforTestcaseExecution(){18 LocalTime openingTime = LocalTime.parse("10:30:00");19 LocalTime closingTime = LocalTime.parse("22:00:00");20 restaurant =new Restaurant("Amelie's cafe","Chennai",openingTime,closingTime);21 restaurant.addToMenu("Sweet corn soup",119);22 restaurant.addToMenu("Vegetable lasagne", 269);23 }242526 //>>>>>>>>>>>>>>>>>>>>>>>>>OPEN/CLOSED<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<27 //-------FOR THE 2 TESTS BELOW, YOU MAY USE THE CONCEPT OF MOCKING, IF YOU RUN INTO ANY TROUBLE28 @Test29 public void is_restaurant_open_should_return_true_if_time_is_between_opening_and_closing_time(){30 addMenuforTestcaseExecution();31 Restaurant spyRestaurant = Mockito.spy(restaurant);32 LocalTime timeForOpenHours = LocalTime.parse("12:30:00");3334 Mockito.spy(when(spyRestaurant.getCurrentTime()).thenReturn(timeForOpenHours));35 spyRestaurant.openingTime = LocalTime.parse("11:00:00");36 spyRestaurant.closingTime = LocalTime.parse("19:00:00");37 assertTrue(spyRestaurant.isRestaurantOpen());3839 }4041 @Test42 public void is_restaurant_open_should_return_false_if_time_is_outside_opening_and_closing_time(){43 addMenuforTestcaseExecution();44 Restaurant spyRestaurant = Mockito.spy(restaurant);45 LocalTime timeForOpenHours = LocalTime.parse("10:30:00");46 Mockito.spy(when(spyRestaurant.getCurrentTime()).thenReturn(timeForOpenHours));47 spyRestaurant.openingTime = LocalTime.parse("11:00:00");48 spyRestaurant.closingTime = LocalTime.parse("19:00:00");49 assertFalse(spyRestaurant.isRestaurantOpen());5051 }525354 //Solution for part-355 @Test56 public void order_total_should_return_total_order_value_when_items_are_ordered_from_menu(){57 addMenuforTestcaseExecution();58 List<String> menuItemNames = Arrays.asList("Sweet corn soup","Vegetable lasagne");5960 assertEquals(388,restaurant.orderTotal(menuItemNames));61 }
...
Source:BaseTest.java
1package ru.shishmakov;2import org.junit.Before;3import org.junit.Rule;4import org.junit.rules.TestName;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.MockitoAnnotations;8import org.mockito.Spy;9import org.slf4j.Logger;10import org.slf4j.LoggerFactory;11import ru.shishmakov.config.ElevatorConfig;12import ru.shishmakov.core.Command;13import ru.shishmakov.core.Inbound;14import ru.shishmakov.core.TimeController;15import ru.shishmakov.core.state.IdleState;16import ru.shishmakov.core.state.MoveUpOrDownState;17import ru.shishmakov.core.state.StopCloseState;18import ru.shishmakov.core.state.StopOpenState;19import javax.inject.Provider;20import java.util.concurrent.ArrayBlockingQueue;21import java.util.concurrent.BlockingQueue;22import static org.mockito.Mockito.doReturn;23/**24 * Base class for JUnit test classes.25 *26 * @author Dmitriy Shishmakov on 06.08.1727 */28public abstract class BaseTest {29 /**30 * Logger used by test.31 */32 protected final Logger logger = LoggerFactory.getLogger(this.getClass());33 protected static final long currentTime = System.currentTimeMillis();34 @Spy35 @InjectMocks36 protected IdleState idleState;37 @Spy38 @InjectMocks39 protected MoveUpOrDownState moveUpOrDownState;40 @Spy41 @InjectMocks42 protected StopOpenState stopOpenState;43 @Spy44 @InjectMocks45 protected StopCloseState stopCloseState;46 @Spy47 protected Inbound inbound = Inbound.buildInbound(new String[]{"-n", "15", "-h", "4", "-v", "2", "-d", "10"});48 @Spy49 protected BlockingQueue<Command> elevatorCommands = new ArrayBlockingQueue<>(1);50 @Spy51 protected TimeController timeController;52 @Mock(name = "idleProvider")53 protected Provider<IdleState> idleProvider;54 @Mock(name = "moveUpOrDownProvider")55 protected Provider<MoveUpOrDownState> moveUpOrDownProvider;56 @Mock(name = "stopCloseProvider")57 protected Provider<StopCloseState> stopCloseProvider;58 @Mock(name = "stopOpenProvider")59 protected Provider<StopOpenState> stopOpenProvider;60 @Mock61 protected ElevatorConfig config;62 @Rule63 public TestName testName = new TestName();64 @Before65 public void setUp() {66 logTestStart();67 MockitoAnnotations.initMocks(this);68 doReturn(currentTime).when(timeController).now();69 doReturn(idleState).when(idleProvider).get();70 doReturn(moveUpOrDownState).when(moveUpOrDownProvider).get();71 doReturn(stopOpenState).when(stopOpenProvider).get();72 doReturn(stopCloseState).when(stopCloseProvider).get();73 }74 private void logTestStart() {75 logger.info("Running test \"{}\"", testName.getMethodName());76 }77}...
open
Using AI Code Generation
1import org.mockito.Spy;2import java.util.ArrayList;3import java.util.List;4import java.util.Scanner;5public class SpyExample {6 public static void main(String[] args) {7 List<String> list = new ArrayList<String>();8 Scanner sc = new Scanner(System.in);9 System.out.println("Enter the number of elements");10 int n = sc.nextInt();11 System.out.println("Enter the elements");12 for (int i = 0; i < n; i++) {13 list.add(sc.next());14 }15 System.out.println("The elements in the list are: " + list);16 }17}
open
Using AI Code Generation
1package com.ack.j2se.mockitotest;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.spy;4import static org.mockito.Mockito.when;5import java.util.List;6public class MockitoSpyTest {7 public static void main( String[] args ) {8 List list = mock( List.class );9 List spyList = spy( list );10 when( spyList.size() ).thenReturn( 100 );11 System.out.println( "size of spyList is " + spyList.size() );12 System.out.println( "size of list is " + list.size() );13 }14}
open
Using AI Code Generation
1package org.mockito;2import java.util.ArrayList;3public class Spy {4 public static void main(String[] args) {5 ArrayList<String> list = new ArrayList<String>();6 ArrayList<String> spy = Mockito.spy(list);7 spy.add("one");8 spy.add("two");9 System.out.println(spy.get(0));10 System.out.println(spy.size());11 Mockito.verify(spy).add("one");12 Mockito.verify(spy).add("two");13 }14}
open
Using AI Code Generation
1package org.mockito;2import org.mockito.Spy;3import org.mockito.Mock;4import org.mockito.Mockito;5import org.mockito.MockitoAnnotations;6import org.mockito.InjectMocks;7import org.mockito.MockitoAnnotations;
open
Using AI Code Generation
1package com.ack.open;2import org.mockito.Spy;3public class SpyOpen {4 public static void main(String[] args) {5 Spy spy = new Spy();6 spy.open();7 }8}
open
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.Spy;3public class SpyDemo {4 public static void main(String[] args) {5 String str = Mockito.spy(String.class);6 str.length();7 str.toString();8 }9}
open
Using AI Code Generation
1package org.mockito;2import java.util.*;3import static org.mockito.Mockito.*;4import java.io.*;5import java.util.Scanner;6public class Spy {7 public static void main(String[] args) {8 List list = mock(List.class);9 when(list.get(0)).thenReturn("first");10 when(list.get(1)).thenReturn("second");11 List spy = spy(list);12 System.out.println(spy.get(999));13 System.out.println(spy.get(0));14 System.out.println(spy.get(1));15 when(spy.size()).thenReturn(100);16 System.out.println(spy.size());17 verify(spy).get(0);18 }19}20package org.mockito;21import java.util.*;22import static org.mockito.Mockito.*;23import java.io.*;24import java.util.Scanner;25public class Spy {26 public static void main(String[] args) {27 List list = mock(List.class);28 when(list.get(0)).thenReturn("first");29 when(list.get(1)).thenReturn("second");30 List spy = spy(list);31 System.out.println(spy.get(999));32 System.out.println(spy.get(0));33 System.out.println(spy.get(1));34 when(spy.size()).thenReturn(100);35 System.out.println(spy.size());36 verify(spy).get(0);37 doReturn("foo").when(spy).get(0);38 System.out.println(spy.get(0));39 }40}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!