类org.mockito.AdditionalAnswers源码实例Demo

下面列出了怎么用org.mockito.AdditionalAnswers的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: syndesis   文件: ConnectorHandlerTest.java
@Test
public void shouldVerifyUserPropertiesOverrideConfiguredProperties() {
    final EncryptionComponent encryptionComponent = mock(EncryptionComponent.class);
    final Verifier verifier = new Verifier() {
        @Override
        public List<Result> verify(String connectorId, Map<String, String> parameters) {
            assertThat(parameters).containsEntry("configuredProperty","val2");
            return null;
        }
    };
    final ConnectorHandler connectorHandler = new ConnectorHandler(dataManager, verifier , NO_CREDENTIALS, NO_INSPECTORS, NO_STATE,
        encryptionComponent, applicationContext, NO_ICON_DAO, NO_EXTENSION_DATA_MANAGER,
        NO_METADATA_CONFIGURATION_PROPERTIES);

    final Connector connector = new Connector.Builder()
        .id("connectorId")
        .putConfiguredProperty("configuredProperty","val1")
        .build();
    when(dataManager.fetch(Connector.class,"connectorId")).thenReturn(connector);
    when(dataManager.fetchAll(Integration.class)).thenReturn(() -> 0);
    Map<String, String> mutableMapParams = new HashMap<>(10);
    mutableMapParams.put("configuredProperty", "val2");
    when(encryptionComponent.decrypt(anyMap())).then(AdditionalAnswers.returnsFirstArg());

    connectorHandler.verifyConnectionParameters("connectorId", mutableMapParams);
}
 
源代码2 项目: bullet-core   文件: QuerierTest.java
@Test
public void testRawQueriesWithoutWindowsThatAreTimedOutAreStillRecordBased() {
    BulletConfig config = new BulletConfig();
    config.set(BulletConfig.RAW_AGGREGATION_MAX_SIZE, 10);
    config.validate();

    Query query = makeRawQuery();
    query.configure(config);

    RunningQuery runningQuery = spy(makeRunningQuery("", query));
    Mockito.doAnswer(AdditionalAnswers.returnsElementsOf(Arrays.asList(false, true))).when(runningQuery).isTimedOut();

    Querier querier = new Querier(Querier.Mode.ALL, runningQuery, config);

    Assert.assertFalse(querier.isClosed());
    Assert.assertTrue(querier.shouldBuffer());
    Assert.assertEquals(querier.getWindow().getClass(), Basic.class);

    IntStream.range(0, 9).forEach(i -> querier.consume(RecordBox.get().getRecord()));

    Assert.assertFalse(querier.isClosed());
    // Now runningQuery is timed out but query is not done.
    Assert.assertTrue(querier.shouldBuffer());
}
 
@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());

  RunConfiguration config =
      new LocalAppEngineServerLaunchConfigurationDelegate().generateServerRunConfiguration(
          launchConfiguration, server, ILaunchManager.RUN_MODE, services);
  assertNull(config.getHost());
  assertEquals((Integer) LocalAppEngineServerBehaviour.DEFAULT_SERVER_PORT, config.getPort());
  assertTrue(config.getJvmFlags().isEmpty());
  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);

  RunConfiguration config =
      new LocalAppEngineServerLaunchConfigurationDelegate().generateServerRunConfiguration(
          launchConfiguration, server, ILaunchManager.RUN_MODE, services);

  Integer port = config.getPort();
  assertNotNull(port);
  assertEquals(9999, (int) port);
  verify(launchConfiguration)
      .getAttribute(eq(LocalAppEngineServerBehaviour.SERVER_PORT_ATTRIBUTE_NAME), anyInt());
  verify(server, never()).getAttribute(anyString(), anyInt());
}
 
源代码6 项目: ogham   文件: SendGridFluentEmailTest.java
@BeforeEach
public void setup() {
	when(generator.generate(anyString())).then(AdditionalAnswers.returnsArgAt(0));
	server = new WireMockServer(options().dynamicPort());
	server.start();
	messagingService = MessagingBuilder.standard()
			.email()
				.images()
					.inline()
						.attach()
							.cid()
								.generator(generator)
								.and()
							.and()
						.and()
					.and()
				.sender(SendGridV4Builder.class)
					.url("http://localhost:"+server.port())
					.apiKey("foobar")
					.and()
				.and()
			.build();
}
 
源代码7 项目: ogham   文件: SendGridHttpTest.java
@BeforeEach
public void setup() {
	when(generator.generate(anyString())).then(AdditionalAnswers.returnsArgAt(0));
	server = new WireMockServer(options().dynamicPort());
	server.start();
	messagingService = MessagingBuilder.standard()
			.email()
				.images()
					.inline()
						.attach()
							.cid()
								.generator(generator)
								.and()
							.and()
						.and()
					.and()
				.sender(SendGridV4Builder.class)
					.url("http://localhost:"+server.port())
					.apiKey("foobar")
					.and()
				.and()
			.build();
}
 
源代码8 项目: ogham   文件: SendGridFluentEmailTest.java
@BeforeEach
public void setup() {
	when(generator.generate(anyString())).then(AdditionalAnswers.returnsArgAt(0));
	server = new WireMockServer(options().dynamicPort());
	server.start();
	messagingService = MessagingBuilder.standard()
			.email()
				.images()
					.inline()
						.attach()
							.cid()
								.generator(generator)
								.and()
							.and()
						.and()
					.and()
				.sender(SendGridV2Builder.class)
					.url("http://localhost:"+server.port())
					.apiKey("foobar")
					.and()
				.and()
			.build();
}
 
源代码9 项目: ogham   文件: SendGridHttpTest.java
@BeforeEach
public void setup() {
	when(generator.generate(anyString())).then(AdditionalAnswers.returnsArgAt(0));
	server = new WireMockServer(options().dynamicPort());
	server.start();
	messagingService = MessagingBuilder.standard()
			.email()
				.images()
					.inline()
						.attach()
							.cid()
								.generator(generator)
								.and()
							.and()
						.and()
					.and()
				.sender(SendGridV2Builder.class)
					.url("http://localhost:"+server.port())
					.apiKey("foobar")
					.and()
				.and()
			.build();
}
 
源代码10 项目: bazel   文件: HttpCacheClientTest.java
public UnixDomainServer(
    Class<? extends ServerChannel> serverChannelClass,
    IntFunction<EventLoopGroup> newEventLoopGroup) {
  EventLoopGroup eventLoop = newEventLoopGroup.apply(1);
  ServerBootstrap sb =
      new ServerBootstrap()
          .group(eventLoop)
          .channel(serverChannelClass)
          .childHandler(
              new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) {
                  ch.pipeline().addLast(new HttpServerCodec());
                  ch.pipeline().addLast(new HttpObjectAggregator(1000));
                  ch.pipeline().addLast(Preconditions.checkNotNull(handler));
                }
              });
  try {
    ServerChannel actual = ((ServerChannel) sb.bind(newDomainSocketAddress()).sync().channel());
    this.serverChannel = mock(ServerChannel.class, AdditionalAnswers.delegatesTo(actual));
  } catch (Exception e) {
    throw new IllegalStateException(e);
  }
}
 
源代码11 项目: feign   文件: ReactiveFeignIntegrationTest.java
@Test
public void testResponseMappers() throws Exception {
  this.webServer.enqueue(new MockResponse().setBody("1.0"));

  ResponseMapper responseMapper = mock(ResponseMapper.class);
  Decoder decoder = mock(Decoder.class);
  given(responseMapper.map(any(Response.class), any(Type.class)))
      .willAnswer(AdditionalAnswers.returnsFirstArg());
  given(decoder.decode(any(Response.class), any(Type.class))).willReturn("1.0");

  TestReactorService service = ReactorFeign.builder()
      .mapAndDecode(responseMapper, decoder)
      .target(TestReactorService.class, this.getServerUrl());
  StepVerifier.create(service.version())
      .expectNext("1.0")
      .expectComplete()
      .verify();
  verify(responseMapper, times(1))
      .map(any(Response.class), any(Type.class));
  verify(decoder, times(1)).decode(any(Response.class), any(Type.class));
}
 
源代码12 项目: syndesis   文件: ConnectorHandlerTest.java
@Test
public void shouldVerifyConfiguredProperties() {
    final EncryptionComponent encryptionComponent = mock(EncryptionComponent.class);
    final Verifier verifier = new Verifier() {
        @Override
        public List<Result> verify(String connectorId, Map<String, String> parameters) {
            assertThat(parameters).containsEntry("configuredProperty","val0");
            assertThat(parameters).containsEntry("userProperty","val1");
            return null;
        }
    };
    final ConnectorHandler connectorHandler = new ConnectorHandler(dataManager, verifier , NO_CREDENTIALS, NO_INSPECTORS, NO_STATE,
        encryptionComponent, applicationContext, NO_ICON_DAO, NO_EXTENSION_DATA_MANAGER,
        NO_METADATA_CONFIGURATION_PROPERTIES);

    final Connector connector = new Connector.Builder()
        .id("connectorId")
        .putConfiguredProperty("configuredProperty","val0")
        .build();
    when(dataManager.fetch(Connector.class,"connectorId")).thenReturn(connector);
    when(dataManager.fetchAll(Integration.class)).thenReturn(() -> 0);
    Map<String, String> mutableMapParams = new HashMap<>(10);
    mutableMapParams.put("userProperty", "val1");
    when(encryptionComponent.decrypt(anyMap())).then(AdditionalAnswers.returnsFirstArg());

    connectorHandler.verifyConnectionParameters("connectorId", mutableMapParams);
}
 
private HistoricProcessInstanceQuery mockHistoricProcessInstanceQueryWithPages(List<List<HistoricProcessInstance>> pages) {
    HistoricProcessInstanceQuery historicProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class);
    when(historicProcessInstanceQuery.startedBefore(EXPIRATION_TIME)).thenReturn(historicProcessInstanceQuery);
    when(historicProcessInstanceQuery.finished()).thenReturn(historicProcessInstanceQuery);
    when(historicProcessInstanceQuery.excludeSubprocesses(anyBoolean())).thenReturn(historicProcessInstanceQuery);
    when(historicProcessInstanceQuery.listPage(anyInt(), anyInt())).thenAnswer(AdditionalAnswers.returnsElementsOf(pages));
    long processesCount = getTotalProcessesCount(pages);
    when(historicProcessInstanceQuery.count()).thenReturn(processesCount);
    return historicProcessInstanceQuery;
}
 
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 testFromLaunchConfiguration_defaultRunner() throws CoreException {
  ILaunchConfiguration empty =
      mock(ILaunchConfiguration.class, AdditionalAnswers.returnsSecondArg());
  PipelineLaunchConfiguration launchConfiguration =
      PipelineLaunchConfiguration.fromLaunchConfiguration(majorVersion, empty);
  assertEquals(PipelineLaunchConfiguration.defaultRunner(majorVersion),
      launchConfiguration.getRunner());
}
 
@Test
public void testGenerateRunConfiguration_withHost() throws CoreException {
  when(launchConfiguration.getAttribute(anyString(), anyString()))
      .thenAnswer(AdditionalAnswers.returnsSecondArg());
  when(server.getHost()).thenReturn("example.com");
  RunConfiguration config =
      new LocalAppEngineServerLaunchConfigurationDelegate().generateServerRunConfiguration(
          launchConfiguration, server, ILaunchManager.RUN_MODE, services);
  assertEquals("example.com", config.getHost());
  verify(server, atLeastOnce()).getHost();
}
 
源代码17 项目: google-cloud-eclipse   文件: GcpLocalRunTabTest.java
@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);
}
 
源代码18 项目: google-cloud-eclipse   文件: GcpLocalRunTabTest.java
@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));
}
 
源代码19 项目: hono   文件: HonoConnectionImplTest.java
/**
 * Verifies that the attempt to create a sender succeeds when sender never gets credits.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateSenderThatGetsNoCredits(final VertxTestContext ctx) {
    final ProtonSender sender = mock(ProtonSender.class);
    when(sender.isOpen()).thenReturn(Boolean.TRUE);
    when(con.createSender(anyString())).thenReturn(sender);
    final Target target = new Target();
    target.setAddress("someAddress");
    when(sender.getRemoteTarget()).thenReturn(target);
    when(sender.getCredit()).thenReturn(0);
    // just invoke openHandler with succeeded future
    doAnswer(AdditionalAnswers.answerVoid(
            (final Handler<AsyncResult<ProtonSender>> handler) -> handler.handle(Future.succeededFuture(sender))))
                    .when(sender).openHandler(VertxMockSupport.anyHandler());
    final Handler<String> remoteCloseHook = VertxMockSupport.mockHandler();

    // GIVEN an established connection
    honoConnection.connect()
        .compose(c -> honoConnection.createSender(
            "target", ProtonQoS.AT_LEAST_ONCE, remoteCloseHook))
        .onComplete(ctx.succeeding(s -> {
                ctx.verify(() -> {
                    assertThat(s).isEqualTo(sender);
                    // sendQueueDrainHandler gets unset
                    verify(sender).sendQueueDrainHandler(null);
                });
                ctx.completeNow();
            }));
}
 
源代码20 项目: shardingsphere   文件: NacosCenterRepositoryTest.java
@Test
public void assertWatch() throws NacosException {
    final String expectValue = "expectValue";
    final String[] actualValue = {null};
    doAnswer(AdditionalAnswers.answerVoid(getListenerAnswer(expectValue))).when(configService).addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> actualValue[0] = dataChangedEvent.getValue();
    REPOSITORY.watch("/sharding/test", listener);
    assertThat(actualValue[0], is(expectValue));
}
 
源代码21 项目: shardingsphere   文件: NacosCenterRepositoryTest.java
@Test
public void assertWatchUpdatedChangedType() throws NacosException {
    final String expectValue = "expectValue";
    final String[] actualValue = {null};
    final ChangedType[] actualType = {null};
    doAnswer(AdditionalAnswers.answerVoid(getListenerAnswer(expectValue))).when(configService).addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> {
        actualValue[0] = dataChangedEvent.getValue();
        actualType[0] = dataChangedEvent.getChangedType();
    };
    REPOSITORY.watch("/sharding/test", listener);
    assertThat(actualValue[0], is(expectValue));
    assertThat(actualType[0], is(ChangedType.UPDATED));
}
 
源代码22 项目: shardingsphere   文件: NacosCenterRepositoryTest.java
@Test
public void assertWatchDeletedChangedType() throws NacosException {
    final ChangedType[] actualType = {null};
    doAnswer(AdditionalAnswers.answerVoid(getListenerAnswer(null))).when(configService).addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> actualType[0] = dataChangedEvent.getChangedType();
    REPOSITORY.watch("/sharding/test", listener);
    assertThat(actualType[0], is(ChangedType.UPDATED));
}
 
源代码23 项目: fullstop   文件: RuleEntityServiceImplTest.java
@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));

}
 
源代码24 项目: fullstop   文件: RuleEntityServiceImplTest.java
@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));
}
 
源代码25 项目: cloudbreak   文件: SecurityConfigServiceTest.java
@Test
public void testSecurityConfigDoesNotExists() {
    SecurityConfig createdSecurityConfig = new SecurityConfig();
    when(tlsSecurityService.generateSecurityKeys(any(Workspace.class))).thenReturn(createdSecurityConfig);
    when(securityConfigRepository.save(any(SecurityConfig.class))).then(AdditionalAnswers.returnsFirstArg());

    SecurityConfig securityConfig = underTest.generateAndSaveSecurityConfig(stack);

    Assert.assertEquals("It should create a new SecurityConfig", createdSecurityConfig, securityConfig);
}
 
源代码26 项目: grpc-java   文件: GrpclbLoadBalancerTest.java
@Override
public Subchannel createSubchannel(CreateSubchannelArgs args) {
  FakeSubchannel subchannel =
      mock(
          FakeSubchannel.class,
          AdditionalAnswers
              .delegatesTo(new FakeSubchannel(args.getAddresses(), args.getAttributes())));
  mockSubchannels.add(subchannel);
  unpooledSubchannelTracker.add(subchannel);
  return subchannel;
}
 
源代码27 项目: grpc-java   文件: OkHttpClientTransportTest.java
/** Set up for test. */
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  frameReader = new MockFrameReader();
  socket = new MockSocket(frameReader);
  MockFrameWriter mockFrameWriter = new MockFrameWriter(socket, capturedBuffer);
  frameWriter = mock(FrameWriter.class, AdditionalAnswers.delegatesTo(mockFrameWriter));
}
 
源代码28 项目: tutorials   文件: BookServiceUnitTest.java
@Test
public void givenSaveMethodMocked_whenSaveInvoked_ThenReturnFirstArgument_UnitTest() {
    Book book = new Book("To Kill a Mocking Bird", "Harper Lee", 256);
    Mockito.when(bookRepository.save(any(Book.class))).then(AdditionalAnswers.returnsFirstArg());

    Book savedBook = bookService.save(book);

    assertEquals(savedBook, book);
}
 
源代码29 项目: tutorials   文件: BookServiceUnitTest.java
@Test
public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnSecondArgument_UnitTest() {
    Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456);
    Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300);
    Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200);

    Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg());

    Book secondBook = bookService.selectRandomBook(book1, book2, book3);

    assertEquals(secondBook, book2);
}
 
源代码30 项目: tutorials   文件: BookServiceUnitTest.java
@Test
public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnLastArgument_UnitTest() {
    Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456);
    Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300);
    Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200);

    Mockito.when(bookRepository.selectRandomBook(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg());

    Book lastBook = bookService.selectRandomBook(book1, book2, book3);
    assertEquals(lastBook, book3);
}
 
 类所在包
 同包方法