org.mockito.AdditionalAnswers Java Examples

The following examples show how to use org.mockito.AdditionalAnswers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalAppEngineServerLaunchConfigurationDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: SendGridFluentEmailTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #3
Source File: SendGridHttpTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #4
Source File: SendGridFluentEmailTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: SendGridHttpTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: HttpCacheClientTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #7
Source File: LocalAppEngineServerLaunchConfigurationDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #8
Source File: LocalAppEngineServerLaunchConfigurationDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: QuerierTest.java    From bullet-core with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: ConnectorHandlerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: ReactiveFeignIntegrationTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: OkHttpClientTransportTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** 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));
}
 
Example #13
Source File: BookServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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);
}
 
Example #14
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #15
Source File: GrpclbLoadBalancerTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #16
Source File: BookServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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);
}
 
Example #17
Source File: SecurityConfigServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: RuleEntityServiceImplTest.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #19
Source File: RuleEntityServiceImplTest.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@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));

}
 
Example #20
Source File: BookServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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);
}
 
Example #21
Source File: BookServiceUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnArgumentAtIndex_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.returnsArgAt(1));

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

    assertEquals(bookOnIndex, book2);
}
 
Example #22
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #23
Source File: ConnectorHandlerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #24
Source File: FlowableHistoricDataCleanerTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: ParsecHttpRequestRetryCallableTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example #26
Source File: MajorVersionPipelineRunnerConfigurationTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #27
Source File: LocalAppEngineServerLaunchConfigurationDelegateTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #28
Source File: GcpLocalRunTabTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: GcpLocalRunTabTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #30
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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();
            }));
}