org.mockito.InOrder Java Examples

The following examples show how to use org.mockito.InOrder. 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: SynchronizationContextTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void taskThrows() {
  InOrder inOrder = inOrder(task1, task2, task3);
  final RuntimeException e = new RuntimeException("Simulated");
  doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) {
        throw e;
      }
    }).when(task2).run();
  syncContext.executeLater(task1);
  syncContext.executeLater(task2);
  syncContext.executeLater(task3);
  syncContext.drain();
  inOrder.verify(task1).run();
  inOrder.verify(task2).run();
  inOrder.verify(task3).run();
  assertThat(uncaughtErrors).containsExactly(e);
  uncaughtErrors.clear();
}
 
Example #2
Source File: LiveDataTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveDuringBringingUpToState() {
    mLiveData.setValue("bla");
    mLiveData.observeForever(new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            mLiveData.removeObserver(this);
        }
    });
    mRegistry.handleLifecycleEvent(ON_RESUME);
    assertThat(mLiveData.hasActiveObservers(), is(false));
    InOrder inOrder = Mockito.inOrder(mActiveObserversChanged);
    inOrder.verify(mActiveObserversChanged).onCall(true);
    inOrder.verify(mActiveObserversChanged).onCall(false);
    inOrder.verifyNoMoreInteractions();
}
 
Example #3
Source File: MouseActionsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void clickElementNotClickableStaleReferenceExceptionNotChrome()
{
    when(webDriverManager.isTypeAnyOf(WebDriverType.CHROME)).thenReturn(false);
    mockBodySearch();

    WebDriverException e = new WebDriverException(ELEMENT_IS_NOT_CLICKABLE_AT_POINT);
    WebDriverException e2 = new WebDriverException(STALE_EXCEPTION);
    doThrow(e).doThrow(e2).when(webElement).click();
    ClickResult result = mouseActions.click(webElement);
    verify(webElement, never()).sendKeys("");
    assertFalse(result.isNewPageLoaded());
    InOrder ordered = inOrder(javascriptActions, alertActions, eventBus, webUiContext, softAssert);
    ordered.verify(javascriptActions).scrollElementIntoViewportCenter(webElement);
    ordered.verify(softAssert).recordFailedAssertion(COULD_NOT_CLICK_ERROR_MESSAGE + e2);
    ordered.verifyNoMoreInteractions();
}
 
Example #4
Source File: LiveDataTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveDuringAddition() {
    mRegistry.handleLifecycleEvent(ON_START);
    mLiveData.setValue("bla");
    mLiveData.observeForever(new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            mLiveData.removeObserver(this);
        }
    });
    assertThat(mLiveData.hasActiveObservers(), is(false));
    InOrder inOrder = Mockito.inOrder(mActiveObserversChanged);
    inOrder.verify(mActiveObserversChanged).onCall(true);
    inOrder.verify(mActiveObserversChanged).onCall(false);
    inOrder.verifyNoMoreInteractions();
}
 
Example #5
Source File: JSchExecutorTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public void shouldFailOnCommandExecutionError() throws Exception
{
    ServerConfiguration server = getDefaultServerConfiguration();
    server.setPublicKey(null);
    JSch jSch = mock(JSch.class);
    whenNew(JSch.class).withNoArguments().thenReturn(jSch);
    Session session = mock(Session.class);
    when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session);
    ChannelExec channelExec = mockChannelOpening(session);
    JSchException jSchException = new JSchException();
    CommandExecutionException exception = assertThrows(CommandExecutionException.class,
        () -> new TestJSchExecutor()
        {
            @Override
            protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands,
                    ChannelExec channel) throws JSchException
            {
                throw jSchException;
            }
        }.execute(server, COMMANDS));
    assertEquals(jSchException, exception.getCause());
    InOrder ordered = inOrder(jSch, session, channelExec);
    verifyFullConnection(ordered, server, session, channelExec);
}
 
Example #6
Source File: FullTraversalConnectorTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeHandlerNoChanges() throws Exception {
  // targets and mocks
  byte[] payload = "Payload Value".getBytes();
  when(checkpointHandlerMock
      .readCheckpoint(FullTraversalConnector.CHECKPOINT_INCREMENTAL))
      .thenReturn(payload);
  when(repositoryMock.getChanges(any())).thenReturn(null);

  // incremental handler test
  FullTraversalConnector connector =
      new FullTraversalConnector(repositoryMock, checkpointHandlerMock);
  setConfig("0", DefaultAclChoices.INDIVIDUAL);
  connector.init(connectorContextMock);
  connector.handleIncrementalChanges();

  // verify
  InOrder inOrderCheck = inOrder(checkpointHandlerMock);
  inOrderCheck.verify(checkpointHandlerMock)
      .readCheckpoint(FullTraversalConnector.CHECKPOINT_QUEUE);
  inOrderCheck.verify(checkpointHandlerMock)
      .readCheckpoint(FullTraversalConnector.CHECKPOINT_INCREMENTAL);
  verifyNoMoreInteractions(checkpointHandlerMock);
}
 
Example #7
Source File: BlockingExecutorTest.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@Test
public void delegateException() throws InterruptedException {
  doThrow(RuntimeException.class).when(delegate).execute(any(Runnable.class));

  underTest = new BlockingExecutor(delegate, semaphore);

  try {
    underTest.execute(runnable);
    fail();
  } catch (RuntimeException e) {
    InOrder inOrder = inOrder(delegate, semaphore);
    inOrder.verify(semaphore).acquire();
    inOrder.verify(delegate).execute(any(Runnable.class));
    inOrder.verify(semaphore).release();
  }
}
 
Example #8
Source File: BlockingExecutorTest.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@Test
public void runnableException() throws InterruptedException {
  doThrow(RuntimeException.class).when(runnable).run();

  underTest = new BlockingExecutor(delegate, semaphore);

  underTest.execute(runnable);
  InOrder inOrder = inOrder(delegate, semaphore);
  inOrder.verify(semaphore).acquire();
  inOrder.verify(delegate).execute(captor.capture());
  inOrder.verify(semaphore, never()).release();

  try {
    captor.getValue().run();
    fail();
  } catch (RuntimeException e) {
    InOrder inOrder2 = inOrder(runnable, semaphore);
    inOrder2.verify(runnable).run();
    inOrder2.verify(semaphore).release();
  }
}
 
Example #9
Source File: IndexingApplicationTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void shutdownWithRunningTraverser() throws InterruptedException {
  when(mockTraverser.isStarted()).thenReturn(true);
  IndexingApplication subject =
      new IndexingApplication.Builder(mockConnector, new String[] {})
          .setIndexingService(mockIndexingService)
          .setHelper(mockHelper)
          .build();
  subject.start();
  subject.shutdown("TestEvent");
  InOrder inOrder = inOrder(spyLogger, mockTraverser, mockConnector);
  inOrder.verify(spyLogger).log(eq(Level.INFO), any(), anyString());
  inOrder.verify(mockTraverser).isStarted();
  inOrder.verify(mockTraverser).stop();
  inOrder.verify(mockConnector).destroy();
}
 
Example #10
Source File: WindowsActionsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testSwitchToWindowWithMatchingTitle()
{
    @SuppressWarnings("unchecked")
    Matcher<String> matcher = mock(Matcher.class);
    TargetLocator targetLocator = mock(TargetLocator.class);
    when(webDriverProvider.get()).thenReturn(webDriver);
    mockWindowHandles(WINDOW3, WINDOW2, WINDOW1);
    when(webDriver.switchTo()).thenReturn(targetLocator).thenReturn(targetLocator);
    when(webDriver.getTitle()).thenReturn(WINDOW3).thenReturn(WINDOW2).thenReturn(WINDOW1);
    when(matcher.matches(WINDOW3)).thenReturn(false);
    when(matcher.matches(WINDOW2)).thenReturn(false);
    when(matcher.matches(WINDOW1)).thenReturn(true);
    InOrder inOrder = Mockito.inOrder(targetLocator, targetLocator);

    assertEquals(WINDOW1, windowsActions.switchToWindowWithMatchingTitle(matcher));
    inOrder.verify(targetLocator).window(WINDOW3);
    inOrder.verify(targetLocator).window(WINDOW2);
    inOrder.verify(targetLocator).window(WINDOW1);
}
 
Example #11
Source File: HttpRequestExecutorTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testExecuteHttpRequestPredicateFunction() throws IOException
{
    HttpResponse httpResponse1 = new HttpResponse();
    httpResponse1.setResponseTimeInMs(0);
    HttpResponse httpResponse2 = new HttpResponse();
    httpResponse2.setResponseTimeInMs(RESPONSE_TIME_IN_MS);
    when(httpClient.execute(argThat(e -> e instanceof HttpRequestBase && URL.equals(e.getURI().toString())),
            nullable(HttpContext.class))).thenReturn(httpResponse1).thenReturn(httpResponse2);
    httpRequestExecutor.executeHttpRequest(HttpMethod.GET, URL, Optional.empty(),
        response -> response.getResponseTimeInMs() >= RESPONSE_TIME_IN_MS, new WaitMode(Duration.ofSeconds(2), 2));
    InOrder orderedHttpTestContext = inOrder(httpTestContext);
    verifyHttpTestContext(orderedHttpTestContext, httpResponse1);
    verifyHttpTestContext(orderedHttpTestContext, httpResponse2);
    orderedHttpTestContext.verify(httpTestContext).releaseRequestData();
    orderedHttpTestContext.verifyNoMoreInteractions();
    assertThat(logger.getLoggingEvents(),
            equalTo(List.of(createResponseTimeLogEvent(httpResponse1), createResponseTimeLogEvent(httpResponse2))));
}
 
Example #12
Source File: BatchedEmbedderTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testRunStoriesAsPaths()
{
    BatchedEmbedder spy = createBatchedEmbedderSpy(true);
    doNothing().when(spy).generateReportsView();
    MetaFilter mockedFilter = mock(MetaFilter.class);
    doReturn(mockedFilter).when(spy).metaFilter();
    List<String> testStoryPaths = List.of(PATH);
    EmbedderControls mockedEmbedderControls = mockEmbedderControls(spy);
    when(mockedEmbedderControls.threads()).thenReturn(THREADS);
    mockBatchExecutionConfiguration(true);
    spy.runStoriesAsPaths(Map.of(BATCH, testStoryPaths));
    InOrder ordered = inOrder(spy, embedderMonitor, storyManager, bddRunContext, bddVariableContext);
    ordered.verify(spy).processSystemProperties();
    ordered.verify(embedderMonitor).usingControls(mockedEmbedderControls);
    List<ExecutorService> service = new ArrayList<>(1);
    ordered.verify(spy).useExecutorService(argThat(service::add));
    ordered.verify(bddRunContext).putRunningBatch(BATCH);
    ordered.verify(storyManager).runStoriesAsPaths(eq(testStoryPaths), eq(mockedFilter), any(BatchFailures.class));
    ordered.verify(bddVariableContext).clearVariables();
    ordered.verify(bddRunContext).removeRunningBatch();
    ordered.verify(spy).generateReportsView();
    ordered.verifyNoMoreInteractions();
    verifyExecutorService(service.get(0));
}
 
Example #13
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnRollback() throws Exception {
	given(con.getAutoCommit()).willReturn(true);
	willThrow(new SQLException("Cannot rollback")).given(con).rollback();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).rollback();
	ordered.verify(con).setAutoCommit(true);
	verify(con).close();
}
 
Example #14
Source File: ApplicationTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void createApplicationAndFullConnectorLifecycle() throws Exception {
  Application<ApplicationHelper, ConnectorContext> subject =
      new Application.Builder(mockConnector, new String[] {})
          .setHelper(mockHelper)
          .build();
  // Stub helper.createTraverserInstance(..) to shoot a traverse callback immediately
  doAnswer(
          invocation -> {
            mockConnector.traverse();
            return mockTraverser;
          })
      .when(mockTraverser)
      .start();

  subject.start();

  // Verify order of callbacks to Connector
  InOrder inOrder = inOrder(mockConnector);
  inOrder.verify(mockConnector).init(mockContext);
  inOrder.verify(mockConnector).traverse();

  subject.shutdown("From Test");
  inOrder.verify(mockConnector).destroy();
}
 
Example #15
Source File: RetriableStreamTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void unretriableClosed_cancel() {
  ClientStream mockStream1 = mock(ClientStream.class);
  doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);
  InOrder inOrder = inOrder(retriableStreamRecorder);

  retriableStream.start(masterListener);

  ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream1).start(sublistenerCaptor1.capture());

  // closed
  Status status = Status.fromCode(NON_RETRIABLE_STATUS_CODE);
  Metadata metadata = new Metadata();
  sublistenerCaptor1.getValue().closed(status, metadata);

  inOrder.verify(retriableStreamRecorder).postCommit();
  verify(masterListener).closed(status, metadata);

  // cancel
  retriableStream.cancel(Status.CANCELLED);
  inOrder.verify(retriableStreamRecorder, never()).postCommit();
}
 
Example #16
Source File: SftpExecutorTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testPopulateErrorStreamOnSftpError() throws Exception
{
    ChannelSftp channel = mock(ChannelSftp.class);
    SftpException sftpException = new SftpException(0, "error");
    doThrow(sftpException).when(channel).pwd();
    ServerConfiguration serverConfiguration = new ServerConfiguration();
    serverConfiguration.setAgentForwarding(true);
    SftpOutput sftpOutput = sftpExecutor.executeCommand(serverConfiguration, new Commands("pwd"), channel);
    assertEquals("", sftpOutput.getResult());
    InOrder ordered = inOrder(channel, softAssert);
    ordered.verify(channel).setAgentForwarding(serverConfiguration.isAgentForwarding());
    ordered.verify(channel).connect();
    ordered.verify(channel).pwd();
    ordered.verify(softAssert).recordFailedAssertion("SFTP command error", sftpException);
    ordered.verifyNoMoreInteractions();
}
 
Example #17
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnRollback() throws Exception {
	given(con.getAutoCommit()).willReturn(true);
	willThrow(new SQLException("Cannot rollback")).given(con).rollback();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).rollback();
	ordered.verify(con).setAutoCommit(true);
	verify(con).close();
}
 
Example #18
Source File: RetriableStreamTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void headersRead_cancel() {
  ClientStream mockStream1 = mock(ClientStream.class);
  doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);
  InOrder inOrder = inOrder(retriableStreamRecorder);

  retriableStream.start(masterListener);

  ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream1).start(sublistenerCaptor1.capture());

  sublistenerCaptor1.getValue().headersRead(new Metadata());

  inOrder.verify(retriableStreamRecorder).postCommit();

  retriableStream.cancel(Status.CANCELLED);

  inOrder.verify(retriableStreamRecorder, never()).postCommit();
}
 
Example #19
Source File: ImportSelectorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void importSelectorsWithNestedGroupSameDeferredImport() {
	DefaultListableBeanFactory beanFactory = spy(new DefaultListableBeanFactory());
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(beanFactory);
	context.register(ParentConfiguration2.class);
	context.refresh();
	InOrder ordered = inOrder(beanFactory);
	ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
	ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
	assertThat(TestImportGroup.instancesCount.get(), equalTo(2));
	assertThat(TestImportGroup.allImports().size(), equalTo(2));
	assertThat(TestImportGroup.allImports(), hasEntry(
			is(ParentConfiguration2.class.getName()),
			IsIterableContainingInOrder.contains(DeferredImportSelector2.class.getName(),
					ChildConfiguration2.class.getName())));
	assertThat(TestImportGroup.allImports(), hasEntry(
			is(ChildConfiguration2.class.getName()),
			IsIterableContainingInOrder.contains(DeferredImportSelector2.class.getName())));
}
 
Example #20
Source File: LifecycleRegistryTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void constructionDestruction2() {
    fullyInitializeRegistry();
    final TestObserver observer = spy(new TestObserver() {
        @Override
        void onStart() {
            dispatchEvent(ON_PAUSE);
            dispatchEvent(ON_STOP);
            dispatchEvent(ON_DESTROY);
        }
    });
    mRegistry.addObserver(observer);
    InOrder orderVerifier = inOrder(observer);
    orderVerifier.verify(observer).onCreate();
    orderVerifier.verify(observer).onStart();
    orderVerifier.verify(observer).onStop();
    orderVerifier.verify(observer).onDestroy();
    orderVerifier.verify(observer, never()).onResume();
}
 
Example #21
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pickAfterStateChangeAfterResolution() throws Exception {
  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  verify(mockHelper).updateBalancingState(eq(CONNECTING), pickerCaptor.capture());
  Subchannel subchannel = pickerCaptor.getValue().pickSubchannel(mockArgs).getSubchannel();
  reset(mockHelper);

  InOrder inOrder = inOrder(mockHelper);

  Status error = Status.UNAVAILABLE.withDescription("boom!");
  loadBalancer.handleSubchannelState(subchannel,
      ConnectivityStateInfo.forTransientFailure(error));
  inOrder.verify(mockHelper).updateBalancingState(eq(TRANSIENT_FAILURE), pickerCaptor.capture());
  assertEquals(error, pickerCaptor.getValue().pickSubchannel(mockArgs).getStatus());

  loadBalancer.handleSubchannelState(subchannel, ConnectivityStateInfo.forNonError(IDLE));
  inOrder.verify(mockHelper).updateBalancingState(eq(IDLE), pickerCaptor.capture());
  assertEquals(Status.OK, pickerCaptor.getValue().pickSubchannel(mockArgs).getStatus());

  loadBalancer.handleSubchannelState(subchannel, ConnectivityStateInfo.forNonError(READY));
  inOrder.verify(mockHelper).updateBalancingState(eq(READY), pickerCaptor.capture());
  assertEquals(subchannel, pickerCaptor.getValue().pickSubchannel(mockArgs).getSubchannel());

  verifyNoMoreInteractions(mockHelper);
}
 
Example #22
Source File: PickFirstLoadBalancerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pickAfterResolvedAndChanged() throws Exception {
  SocketAddress socketAddr = new FakeSocketAddress("newserver");
  List<EquivalentAddressGroup> newServers =
      Lists.newArrayList(new EquivalentAddressGroup(socketAddr));

  InOrder inOrder = inOrder(mockHelper);

  loadBalancer.handleResolvedAddressGroups(servers, affinity);
  inOrder.verify(mockHelper).createSubchannel(eq(servers), any(Attributes.class));
  inOrder.verify(mockHelper).updateBalancingState(eq(CONNECTING), pickerCaptor.capture());
  verify(mockSubchannel).requestConnection();
  assertEquals(mockSubchannel, pickerCaptor.getValue().pickSubchannel(mockArgs).getSubchannel());

  loadBalancer.handleResolvedAddressGroups(newServers, affinity);
  inOrder.verify(mockHelper).updateSubchannelAddresses(eq(mockSubchannel), eq(newServers));

  verifyNoMoreInteractions(mockSubchannel);
  verifyNoMoreInteractions(mockHelper);
}
 
Example #23
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testItemAndContentNotIncrement() throws IOException, InterruptedException {
  Item item = new Item().setName("id1").setAcl(getCustomerAcl());
  AbstractInputStreamContent content = ByteArrayContent.fromString("", "golden");
  RepositoryDoc doc =
      new RepositoryDoc.Builder()
          .setItem(item)
          .setContent(content, ContentFormat.TEXT)
          .setRequestMode(RequestMode.ASYNCHRONOUS)
          .build();
  SettableFuture<Item> updateFuture = SettableFuture.create();

  doAnswer(
          invocation -> {
            updateFuture.set(new Item());
            return updateFuture;
          })
      .when(mockIndexingService)
      .indexItemAndContent(
          any(), any(), any(), eq(ContentFormat.TEXT), eq(RequestMode.ASYNCHRONOUS));

  doc.execute(mockIndexingService);

  InOrder inOrder = inOrder(mockIndexingService);
  inOrder
      .verify(mockIndexingService)
      .indexItemAndContent(item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);
}
 
Example #24
Source File: RetriableStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cancel_closed() {
  ClientStream mockStream1 = mock(ClientStream.class);
  doReturn(mockStream1).when(retriableStreamRecorder).newSubstream(0);
  InOrder inOrder = inOrder(retriableStreamRecorder);

  retriableStream.start(masterListener);

  ArgumentCaptor<ClientStreamListener> sublistenerCaptor1 =
      ArgumentCaptor.forClass(ClientStreamListener.class);
  verify(mockStream1).start(sublistenerCaptor1.capture());

  // cancel
  retriableStream.cancel(Status.CANCELLED);

  inOrder.verify(retriableStreamRecorder).postCommit();
  ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
  verify(mockStream1).cancel(statusCaptor.capture());
  assertEquals(Status.CANCELLED.getCode(), statusCaptor.getValue().getCode());
  assertEquals(CANCELLED_BECAUSE_COMMITTED, statusCaptor.getValue().getDescription());

  // closed even with retriable status
  Status status = Status.fromCode(RETRIABLE_STATUS_CODE_1);
  Metadata metadata = new Metadata();
  sublistenerCaptor1.getValue().closed(status, metadata);
  inOrder.verify(retriableStreamRecorder, never()).postCommit();
}
 
Example #25
Source File: WebElementActionsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testTypeTextIExploreRequireWindowFocusTrueWithoutReentering()
{
    Mockito.lenient().when(webDriverManager.isTypeAnyOf(WebDriverType.IEXPLORE)).thenReturn(true);
    mockRequireWindowFocusOption(true);
    when(baseValidations.assertIfElementExists(ATTRIBUTES, searchAttributes)).thenReturn(webElement);
    when(javascriptActions.executeScript(GET_ELEMENT_VALUE_JS, webElement)).thenReturn(TEXT);
    webElementActions.typeText(searchAttributes, TEXT);
    InOrder inOrder = inOrder(webElement);
    inOrder.verify(webElement).clear();
    inOrder.verify(webElement).sendKeys(TEXT);
}
 
Example #26
Source File: ListingConnectorTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testTraverseAbortOnError() throws Exception {
  setDefaultConfig();
  PushItem pushItem = new PushItem();
  ApiOperation pushOperation = new PushItems.Builder().addPushItem("pushedId", pushItem).build();
  ApiOperation deleteOperation = ApiOperations.deleteItem("deletedItem");
  Collection<ApiOperation> operations =
      Arrays.asList(pushOperation, errorOperation, deleteOperation);
  TestCloseableIterable delegate = new TestCloseableIterable(operations);
  CheckpointCloseableIterable<ApiOperation> testIterable =
      new CheckpointCloseableIterableImpl.Builder<>(delegate).build();
  when(mockRepository.getIds(any())).thenReturn(testIterable);
  ListingConnector connector = new ListingConnector(mockRepository, mockCheckpointHandler);
  connector.init(mockConnectorContext);
  SettableFuture<Item> pushFuture = SettableFuture.create();
  doAnswer(
          invocation -> {
            pushFuture.set(new Item());
            return pushFuture;
          })
      .when(mockIndexingService)
      .push(eq("pushedId"), eq(pushItem));
  try {
    connector.traverse();
    fail("missing IOException");
  } catch (IOException expected) {
  }
  InOrder inOrder = Mockito.inOrder(mockIndexingService);
  inOrder.verify(mockIndexingService).push("pushedId", pushItem);
  assertTrue(delegate.isClosed());
}
 
Example #27
Source File: SubStepsTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldExecuteSubStepAndThrowWrappedInterruptedException()
{
    StepResult stepResult = mock(StepResult.class);
    InOrder ordered = inOrder(subStepsListener, step, stepResult);
    when(step.perform(storyReporter, null)).thenReturn(stepResult);
    when(stepResult.getFailure()).thenReturn(new UUIDExceptionWrapper(new InterruptedException()));
    assertThrows(IllegalStateException.class, () -> subSteps.execute(Optional.empty()));

    ordered.verify(subStepsListener).beforeSubSteps();
    ordered.verify(stepResult).describeTo(storyReporter);
    ordered.verify(stepResult).getFailure();
    ordered.verifyNoMoreInteractions();
}
 
Example #28
Source File: DelayedStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void setStream_setAuthority() {
  final String authority = "becauseIsaidSo";
  stream.setAuthority(authority);
  stream.start(listener);
  stream.setStream(realStream);
  InOrder inOrder = inOrder(realStream);
  inOrder.verify(realStream).setAuthority(authority);
  inOrder.verify(realStream).start(any(ClientStreamListener.class));
}
 
Example #29
Source File: TrieIteratorTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "MathAbsoluteRandom"})
public void shouldIterateArbitraryStructureAccurately() {
  Node<String> root = NullNode.instance();
  final NavigableSet<Bytes32> expectedKeyHashes = new TreeSet<>();
  final Random random = new Random(-5407159858935967790L);
  Bytes32 startAtHash = Bytes32.ZERO;
  Bytes32 stopAtHash = Bytes32.ZERO;
  final int totalNodes = Math.abs(random.nextInt(1000));
  final int startNodeNumber = random.nextInt(Math.max(1, totalNodes - 1));
  final int stopNodeNumber = random.nextInt(Math.max(1, totalNodes - 1));
  for (int i = 0; i < totalNodes; i++) {
    final Bytes32 keyHash =
        Hash.keccak256(UInt256.valueOf(Math.abs(random.nextLong())).toBytes());
    root = root.accept(new PutVisitor<>(nodeFactory, "Value"), bytesToPath(keyHash));
    expectedKeyHashes.add(keyHash);
    if (i == startNodeNumber) {
      startAtHash = keyHash;
    } else if (i == stopNodeNumber) {
      stopAtHash = keyHash;
    }
  }

  final Bytes32 actualStopAtHash =
      stopAtHash.compareTo(startAtHash) >= 0 ? stopAtHash : startAtHash;
  when(leafHandler.onLeaf(any(Bytes32.class), any(Node.class))).thenReturn(State.CONTINUE);
  when(leafHandler.onLeaf(eq(actualStopAtHash), any(Node.class))).thenReturn(State.STOP);
  root.accept(iterator, bytesToPath(startAtHash));
  final InOrder inOrder = inOrder(leafHandler);
  expectedKeyHashes
      .subSet(startAtHash, true, actualStopAtHash, true)
      .forEach(keyHash -> inOrder.verify(leafHandler).onLeaf(eq(keyHash), any(Node.class)));
  verifyNoMoreInteractions(leafHandler);
}
 
Example #30
Source File: HttpServerInitializerTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitChannel() throws Exception {
    // Mock Objects
    HttpServerInitializer httpServerInitializer = mock(HttpServerInitializer.class);
    SocketChannel socketChannel = mock(SocketChannel.class);
    ChannelPipeline channelPipeline = mock(ChannelPipeline.class);

    // Mock SocketChannel#pipeline() method
    when(socketChannel.pipeline()).thenReturn(channelPipeline);

    // HttpServerInitializer#initChannel(SocketChannel) call real method
    doCallRealMethod().when(httpServerInitializer).initChannel(socketChannel);

    // Start test for HttpServerInitializer#initChannel(SocketChannel)
    httpServerInitializer.initChannel(socketChannel);

    // Verify 4 times calling ChannelPipeline#addLast() method
    verify(channelPipeline, times(4)).addLast(any(ChannelHandler.class));

    // Verify the order of calling ChannelPipeline#addLast() method
    InOrder inOrder = inOrder(channelPipeline);
    inOrder.verify(channelPipeline).addLast(any(HttpRequestDecoder.class));
    inOrder.verify(channelPipeline).addLast(any(HttpObjectAggregator.class));
    inOrder.verify(channelPipeline).addLast(any(HttpResponseEncoder.class));

    inOrder.verify(channelPipeline).addLast(any(HttpServerHandler.class));
}