@Before public void setUp() throws Exception { configureForThemes(); configureForUIThread(); mMockContext = mock(Context.class, AdditionalAnswers.delegatesTo(getContext())); doReturn(InstrumentationRegistry.getTargetContext().getMainLooper()) .when(mMockContext).getMainLooper(); mHelper = new WorkspaceHelper(mMockContext); mViewFactory = new TestableBlockViewFactory(mMockContext, mHelper); mController = new BlocklyController.Builder(mMockContext) .setWorkspaceHelper(mHelper) .setBlockViewFactory(mViewFactory) .addBlockDefinitionsFromAsset("default/test_blocks.json") .build(); mController.addCallback(mCallback); mController.setVariableCallback(mVariableCallback); mBlockFactory = mController.getBlockFactory(); mWorkspace = mController.getWorkspace(); mConnectionManager = mController.getWorkspace().getConnectionManager(); mWorkspaceView = new WorkspaceView(getContext()); }
@Test public void update() throws Exception { // data String id = UUID.randomUUID().toString(); int ratingAdjustment = 32; int newGames = 1; int newWins = 1; int newLosses = 0; PlayerRecord existingRecord = PlayerRecord.builder() .id(id) .currentRating(1200) .gamesPlayed(1) .wins(1) .losses(0) .build(); // mocks PlayerDao playerDao = Mockito.mock(PlayerDao.class); Mockito.when(playerDao.update(Mockito.any(PlayerRecord.class))).then(AdditionalAnswers.returnsFirstArg()); Mockito.when(playerDao.findOne(id)).thenReturn(existingRecord); PlayerService instance = new PlayerService(playerDao); Player updated = instance.update(id, ratingAdjustment, newGames, newWins, newLosses); Assert.assertEquals(existingRecord.getCurrentRating() + ratingAdjustment, updated.getCurrentRating()); }
@Before public void setUp() throws CoreException { when(launchConfiguration.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(launchConfiguration.getAttribute(anyString(), anyInt())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(launchConfiguration.getAttribute(anyString(), anyBoolean())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.getAttribute(anyString(), anyInt())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.getAttribute(anyString(), anyBoolean())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.loadAdapter(any(Class.class), any(IProgressMonitor.class))) .thenReturn(serverBehavior); }
@Test public void testGenerateRunConfiguration() throws CoreException { when(launchConfiguration.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(launchConfiguration.getAttribute(anyString(), anyInt())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.getAttribute(anyString(), anyInt())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); DefaultRunConfiguration config = new LocalAppEngineServerLaunchConfigurationDelegate() .generateServerRunConfiguration(launchConfiguration, server, ILaunchManager.RUN_MODE); assertNull(config.getHost()); assertEquals((Integer) LocalAppEngineServerBehaviour.DEFAULT_SERVER_PORT, config.getPort()); assertNull(config.getApiPort()); assertNull(config.getJvmFlags()); verify(server, atLeastOnce()).getHost(); verify(launchConfiguration, atLeastOnce()).getAttribute(anyString(), anyInt()); verify(server, atLeastOnce()).getAttribute(anyString(), anyInt()); }
@Test public void testGenerateRunConfiguration_withServerPort() throws CoreException { when(launchConfiguration.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(launchConfiguration .getAttribute(eq(LocalAppEngineServerBehaviour.SERVER_PORT_ATTRIBUTE_NAME), anyInt())) .thenReturn(9999); DefaultRunConfiguration config = new LocalAppEngineServerLaunchConfigurationDelegate() .generateServerRunConfiguration(launchConfiguration, server, ILaunchManager.RUN_MODE); assertNotNull(config.getPort()); assertEquals(9999, (int) config.getPort()); verify(launchConfiguration) .getAttribute(eq(LocalAppEngineServerBehaviour.SERVER_PORT_ATTRIBUTE_NAME), anyInt()); verify(server, never()).getAttribute(anyString(), anyInt()); }
@Test public void testGenerateRunConfiguration_withAdminPortWhenDevAppserver2() throws CoreException { Assume.assumeTrue(LocalAppEngineServerLaunchConfigurationDelegate.DEV_APPSERVER2); when(launchConfiguration.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(launchConfiguration .getAttribute(eq(LocalAppEngineServerBehaviour.ADMIN_PORT_ATTRIBUTE_NAME), anyInt())) .thenReturn(9999); DefaultRunConfiguration config = new LocalAppEngineServerLaunchConfigurationDelegate() .generateServerRunConfiguration(launchConfiguration, server, ILaunchManager.RUN_MODE); assertNull(config.getAdminPort()); verify(launchConfiguration, never()) .getAttribute(eq(LocalAppEngineServerBehaviour.ADMIN_PORT_ATTRIBUTE_NAME), anyInt()); verify(server, never()) .getAttribute(eq(LocalAppEngineServerBehaviour.ADMIN_PORT_ATTRIBUTE_NAME), anyInt()); }
/** * Creates spy on wait function. Spy won't wait and the system time returned will be build from * the given used time millis. So you only need to specify how long each call to the system will * take. * * @param configuredProbe probe to configure wait function for * @param usedTimeMillis array of used times in milliseconds */ private void initSpyOnWaitFunction( ProbeBuilderImpl<SystemUnderTest_SUT, SystemState> configuredProbe, Iterable<Long> usedTimeMillis) { final List<Long> timeMillis = ConcurrentTestUtil.getTimeMillis(usedTimeMillis); configuredProbe.preProcessWaitFunction( new Function<Function<SystemUnderTest_SUT, SystemState>, Function<SystemUnderTest_SUT, SystemState>>() { @Override public Function<SystemUnderTest_SUT, SystemState> apply( Function<SystemUnderTest_SUT, SystemState> input) { WaitFunction<SystemUnderTest_SUT, SystemState> spy = (WaitFunction<SystemUnderTest_SUT, SystemState>) Mockito.spy(input); try { Mockito.doNothing().when(spy).sleep(anyLong()); Mockito.doAnswer( AdditionalAnswers.returnsElementsOf(timeMillis)).when(spy).nowMillis(); } catch (InterruptedException ignored) { } waitFunction = spy; return spy; } }); }
@Before public void setup() { commercialUsageResource = new CommercialUsageResource(); commercialUsageResource.affiliateRepository = affiliateRepository; commercialUsageResource.authorizationChecker = authorizationChecker; commercialUsageResource.commercialUsageRepository = commercialUsageRepository; commercialUsageResource.commercialUsageAuditEvents = commercialUsageAuditEvents; commercialUsageResource.commercialUsageResetter = commercialUsageResetter; this.restCommercialUsageResource = MockMvcBuilders .standaloneSetup(commercialUsageResource) .setMessageConverters(new MockMvcJacksonTestSupport().getConfiguredMessageConverters()) .build(); Mockito.when(commercialUsageRepository.save(Mockito.any(CommercialUsage.class))).then(AdditionalAnswers.returnsFirstArg()); Mockito.when(commercialUsageRepository.saveAndFlush(Mockito.any(CommercialUsage.class))).then(AdditionalAnswers.returnsFirstArg()); withCommercialUsageResetter(); affiliate = new Affiliate(1L); affiliate.setType(AffiliateType.COMMERCIAL); Mockito.when(affiliateRepository.findOne(affiliate.getAffiliateId())).thenReturn(affiliate); }
@Test public void create() throws Exception { PlayerDao playerDao = Mockito.mock(PlayerDao.class); Mockito.when(playerDao.create(Mockito.any(PlayerRecord.class))).then(AdditionalAnswers.returnsFirstArg()); Player toCreate = Player.builder() .userId(UUID.randomUUID().toString()) .build(); PlayerService instance = new PlayerService(playerDao); Player created = instance.create(toCreate); Assert.assertEquals("user id is saved", toCreate.getUserId(), created.getUserId()); Assert.assertNotNull("id is generated", created.getId()); }
private void setMockClientReturnStatusCode(int [] returnStatusCodes) throws Exception { List<ListenableFuture> futures = new ArrayList<>(); for (int returnStatusCode: returnStatusCodes) { com.ning.http.client.Response response = mock(com.ning.http.client.Response.class); when(response.getStatusCode()).thenReturn(returnStatusCode); ListenableFuture future = mock(ListenableFuture.class); when(future.get()).thenReturn(response); futures.add(future); } when(mockClient.executeRequest(request.getNingRequest())) .thenAnswer(AdditionalAnswers.returnsElementsOf(futures)); }
@Test public void testGenerateRunConfiguration_withHost() throws CoreException { when(launchConfiguration.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); when(server.getHost()).thenReturn("example.com"); DefaultRunConfiguration config = new LocalAppEngineServerLaunchConfigurationDelegate() .generateServerRunConfiguration(launchConfiguration, server, ILaunchManager.RUN_MODE); assertEquals("example.com", config.getHost()); verify(server, atLeastOnce()).getHost(); }
@Test public void testGetAttribute_defaultValue() throws CoreException { when(launchConfig.getAttribute(anyString(), anyString())) .then(AdditionalAnswers.returnsLastArg()); String value = GcpLocalRunTab.getAttribute(launchConfig, "non-existing-key", "default"); assertEquals("default", value); }
@Test public void testPerformApply_updatesEnvironmentTab() throws CoreException { when(launchConfig.getAttribute(anyString(), anyString())) .thenAnswer(AdditionalAnswers.returnsSecondArg()); tab.activated(launchConfig); tab.deactivated(launchConfig); verify(environmentTab).initializeFrom(any(ILaunchConfiguration.class)); verify(environmentTab).performApply(any(ILaunchConfigurationWorkingCopy.class)); }
/** * When you mock an interface(or a Class), you can specify a default Answer as well, which * handles interactions you do not declare. * @throws Exception */ @Test public void testInterfaceWithDefaultAnswer() throws Exception { Service mockedObject = mock(Service.class, AdditionalAnswers.delegatesTo(new ServiceImpl())); assertEquals(mockedObject.sayHello(), "hello world"); //still throws a MockitoException //when(mockedObject.sayHello()).thenCallRealMethod(); }
@Test public void whenSaveThenSavedInRepositoryAndMessageSendToTopic() { OpgenomenVermogen opgenomenVermogen = mock(OpgenomenVermogen.class); when(opgenomenVermogenRepository.save(any(OpgenomenVermogen.class))).thenAnswer(AdditionalAnswers.returnsFirstArg()); opgenomenVermogenService.save(opgenomenVermogen); verify(messagingTemplate).convertAndSend(OpgenomenVermogenService.TOPIC, opgenomenVermogen); }
@Test public void testSave() throws Exception { final RuleDTO ruleDTO = new RuleDTO(); ruleDTO.setAccountId("1234"); when(ruleEntityRepository.save(any(RuleEntity.class))).then(AdditionalAnswers.returnsFirstArg()); final RuleEntity savedRuleEntity = ruleEntityServiceImpl.save(ruleDTO); assertThat(savedRuleEntity.getAccountId()).isEqualTo("1234"); assertThat(savedRuleEntity.getExpiryDate()).isEqualTo(new DateTime(9999, 1, 1, 0, 0, 0, UTC)); verify(ruleEntityRepository).save(any(RuleEntity.class)); }
@Test public void testUpdate() throws Exception { final RuleDTO ruleDTO = new RuleDTO(); ruleDTO.setAccountId("5678"); when(ruleEntityRepository.findOne(anyLong())).thenReturn(ruleEntity); when(ruleEntityRepository.save(any(RuleEntity.class))).then(AdditionalAnswers.returnsFirstArg()); final RuleEntity updatedRule = ruleEntityServiceImpl.update(ruleDTO, 1L); assertThat(updatedRule.getAccountId()).isEqualToIgnoringCase("5678"); assertThat(updatedRule.getExpiryDate()).isEqualByComparingTo(new DateTime(9999, 1, 1, 0, 0, 0, UTC)); verify(ruleEntityRepository).findOne(anyLong()); verify(ruleEntityRepository, times(2)).save(any(RuleEntity.class)); }
@Before public void setup() { commercialUsageService = new CommercialUsageService(); commercialUsageService.authorizationChecker = authorizationChecker; commercialUsageService.commercialUsageRepository = commercialUsageRepository; commercialUsageService.commercialUsageAuditEvents = commercialUsageAuditEvents; commercialUsageService.commercialUsageResetter = commercialUsageResetter; Mockito.when(commercialUsageRepository.save(Mockito.any(CommercialUsage.class))).then(AdditionalAnswers.returnsFirstArg()); Mockito.when(commercialUsageRepository.saveAndFlush(Mockito.any(CommercialUsage.class))).then(AdditionalAnswers.returnsFirstArg()); withCommercialUsageResetter(); }
/** * Sets up before each test. * * @throws Exception If error occurred during setup. */ @Before public void setUp() throws Exception { /* Create transport service mock. */ mTransportService = Mockito.mock(TransportService.class); Mockito.when( mTransportService.receive(Mockito.anyString(), Mockito.anyLong())) .thenReturn(new MuleMoverMessage()); /* Create task configuration service mock. */ mTaskConfigurationService = Mockito.mock(TaskConfigurationService.class); Mockito .when( mTaskConfigurationService .save((MessageCowboySchedulableTaskConfig) Mockito .anyObject())).thenAnswer( AdditionalAnswers.returnsFirstArg()); mMoverTask = createFileMoverTask("/SomeInputDir/", "/SomeDestinationDir/"); mTaskJobUnderTest = new QuartzTaskJob(); mJobExecContext = createJobExecutionContextWithMoverTask(mMoverTask); /* * Ensure that before test time will always be smaller the time * obtained by creating a Date instance after this method finishes. */ mBeforeTestTime = new Date(System.currentTimeMillis() - 1); }
@Before public void setUp() throws Exception { mMockContext = mock(Context.class, AdditionalAnswers.delegatesTo(getContext())); mImageFieldView = new BasicFieldImageView(mMockContext); }
@Before public void setUp() throws Exception { configureForThemes(); configureForUIThread(); mMockContext = mock(Context.class, AdditionalAnswers.delegatesTo(getContext())); doReturn(mTargetMainLooper).when(mMockContext).getMainLooper(); mMockController = mock(BlocklyController.class); mMockBlockClipDataHelper = mock(BlockClipDataHelper.class); mMockWorkspace = mock(Workspace.class); mMockConnectionManager = mock(ConnectionManager.class); mDragStartedEvent = mock(DragEvent.class); mDragLocationEvent = mock(DragEvent.class); mDropEvent = mock(DragEvent.class); runAndSync(new Runnable() { @Override public void run() { mBlockFactory = new BlockFactory(); try { mBlockFactory.addJsonDefinitions(mMockContext.getAssets() .open("default/test_blocks.json")); } catch (IOException | BlockLoadingException e) { throw new RuntimeException(e); } mBlockFactory.setController(mMockController); mWorkspaceView = new WorkspaceView(mMockContext); mWorkspaceHelper = new WorkspaceHelper(mMockContext); mWorkspaceHelper.setWorkspaceView(mWorkspaceView); mViewFactory = new VerticalBlockViewFactory(mMockContext, mWorkspaceHelper); // The following are queried by the Dragger. stub(mMockWorkspace.getConnectionManager()).toReturn(mMockConnectionManager); stub(mMockController.getBlockFactory()).toReturn(mBlockFactory); stub(mMockController.getWorkspace()).toReturn(mMockWorkspace); stub(mMockController.getWorkspaceHelper()).toReturn(mWorkspaceHelper); stub(mMockController.getContext()).toReturn(mMockContext); stub(mMockController.getClipDataHelper()).toReturn(mMockBlockClipDataHelper); Mockito.when(mMockBlockClipDataHelper.getPendingDrag(any(DragEvent.class))) .then(new Answer<PendingDrag>() { @Override public PendingDrag answer(InvocationOnMock invocationOnMock) throws Throwable { return mPendingDrag; } }); mDragger = new Dragger(mMockController); mDragger.setWorkspaceView(mWorkspaceView); mTouchHandler = mDragger.buildSloppyBlockTouchHandler(mDragHandler); // Since we can't create DragEvents... when(mDragStartedEvent.getAction()).thenReturn(DragEvent.ACTION_DRAG_STARTED); when(mDragLocationEvent.getAction()).thenReturn(DragEvent.ACTION_DRAG_LOCATION); when(mDropEvent.getAction()).thenReturn(DragEvent.ACTION_DROP); } }); }
@Test public void createLeague() throws Exception { LeagueDao leagueDao = Mockito.mock(LeagueDao.class); PlayerService playerService = Mockito.mock(PlayerService.class); Mockito.when(leagueDao.create(Mockito.any(LeagueRecord.class))).then(AdditionalAnswers.returnsFirstArg()); Mockito.when(playerService.create(Mockito.any(Player.class))).then(AdditionalAnswers.returnsFirstArg()); League toCreate = League.builder().build(); LeagueService leagueService = new LeagueService(leagueDao, playerService); League actual = leagueService.createLeague(toCreate); Assert.assertNotNull("returns created league", actual); Assert.assertNotNull("created league has id", actual.getId()); ArgumentCaptor<Player> createdPlayerCaptor = ArgumentCaptor.forClass(Player.class); Mockito.verify(playerService, Mockito.times(1)).create(createdPlayerCaptor.capture()); Player createdPlayer = createdPlayerCaptor.getValue(); Assert.assertEquals("player created in new league", actual.getId(), createdPlayer.getLeagueId()); }
@Test public void withinMs_configures_timeout_in_milliseconds() throws Exception { String inputValue = "Lorem"; final String outputValue = testName.getMethodName(); String functionName = "Ipsum"; List<Long> timeMillis = Arrays.asList( // init: determine deadline 0L, // cycle 1: determine start time 0L, // cycle 1: determine end time 9L, // cycle 2: determine start time 9L, // cycle 2: determine end time -- timeout 11L); long timeoutMs = 10L; StoreTimeoutEvent<String, String> timeoutFunction = new StoreTimeoutEvent<>(); WaitFunction<String, String> waitFunction = (WaitFunction<String, String>) WaitFunction .waitFor(describe(new Function<String, String>() { @Override public String apply(String input) { return outputValue; } }).as(functionName)) .toFulfill(Predicates.<String>alwaysFalse()) .withinMs(timeoutMs) .onTimeout(timeoutFunction) .get(); WaitFunction<String, String> spy = Mockito.spy(waitFunction); Mockito.doNothing().when(spy).sleep(Mockito.anyLong()); Mockito.doAnswer(AdditionalAnswers.returnsElementsOf(timeMillis)).when(spy).nowMillis(); spy.apply(inputValue); assertThat("Consumed millis greater than or equal to timeout.", timeoutFunction.getLastEvent().getConsumedMs(), Matchers.greaterThanOrEqualTo(timeoutMs)); }
@Test public void raised_timeout_event_contains_all_relevant_information() throws Exception { String inputValue = "Lorem"; final String outputValue = testName.getMethodName(); String functionName = "Ipsum"; long expectedConsumedMs = 11; List<Long> timeMillis = Arrays.asList( // init: determine deadline 5L, // cycle 1: determine start time 5L, // cycle 1: determine end time 5L + expectedConsumedMs); long timeoutMs = 10L; StoreTimeoutEvent<String, String> timeoutFunction = new StoreTimeoutEvent<>(); WaitFunction<String, String> waitFunction = (WaitFunction<String, String>) WaitFunction .waitFor(describe(new Function<String, String>() { @Override public String apply(String input) { return outputValue; } }).as(functionName)) .toFulfill(Predicates.<String>alwaysFalse()) .withinMs(timeoutMs) .onTimeout(timeoutFunction) .get(); WaitFunction<String, String> spy = Mockito.spy(waitFunction); Mockito.doNothing().when(spy).sleep(Mockito.anyLong()); Mockito.doAnswer(AdditionalAnswers.returnsElementsOf(timeMillis)).when(spy).nowMillis(); spy.apply(inputValue); WaitTimeoutEvent<String, String> event = timeoutFunction.getLastEvent(); String eventDescription = event.describe(); String eventToString = event.toString(); // Validate fields errorCollector.checkThat("Event contains item function got applied to.", event.getItem(), Matchers.equalTo(inputValue)); errorCollector.checkThat("Event contains WaitFunction which caused the event.", event.getSource(), Matchers.sameInstance(spy)); errorCollector.checkThat("Event contains result of last apply of function.", event.getLastResult(), Matchers.equalTo(outputValue)); errorCollector.checkThat("Event contains information on consumed milliseconds.", event.getConsumedMs(), Matchers.equalTo(expectedConsumedMs)); // Validate description errorCollector.checkThat("Event description contains item function got applied to.", eventDescription, Matchers.containsString(event.getItem())); errorCollector.checkThat("Event description contains result of last apply of function.", eventDescription, Matchers.containsString(event.getLastResult())); errorCollector.checkThat("Event description contains information on consumed milliseconds.", eventDescription, Matchers.containsString(Long.toString(event.getConsumedMs()))); // Validate toString errorCollector.checkThat("Event toString contains WaitFunction which caused the event.", eventToString, Matchers.containsString(String.valueOf(event.getSource()))); errorCollector.checkThat("Event toString contains item function got applied to.", eventToString, Matchers.containsString(event.getItem())); errorCollector.checkThat("Event toString contains result of last apply of function.", eventToString, Matchers.containsString(event.getLastResult())); errorCollector.checkThat("Event toString contains information on consumed milliseconds.", eventToString, Matchers.containsString(Long.toString(event.getConsumedMs()))); }
public static Region newQueueRegion(ActiveMQServer activeMQServer) { return Mockito.mock(QueueRegion.class, AdditionalAnswers.delegatesTo(new RegionProxy(activeMQServer, RoutingType.ANYCAST))); }
public static Region newTopicRegion(ActiveMQServer activeMQServer) { return Mockito.mock(TopicRegion.class, AdditionalAnswers.delegatesTo(new RegionProxy(activeMQServer, RoutingType.MULTICAST))); }
/** * The way that Robolectric has to implement shadows for Android classes * such as {@link android.content.ContentProvider} is by using a special * annotation that means the classes will implement the correct methods at * runtime. However this means that the shadow of a content provider does * not actually extend {@link android.content.ContentProvider}. As such, * we need to do some special mocking using Mockito in order to provide a * {@link ContextWrapper} which is able to return a proper content * resolver that delegates to the Robolectric shadow object. */ public static ContextWrapper createContextWithContentResolver(ShadowContentResolver contentResolver) { final ContentResolver resolver = mock(ContentResolver.class, AdditionalAnswers.delegatesTo(contentResolver)); return new ContextWrapper(RuntimeEnvironment.application.getApplicationContext()) { @Override public ContentResolver getContentResolver() { return resolver; } }; }