Java Code Examples for org.mockito.InOrder

The following examples show how to use org.mockito.InOrder. These examples are extracted from open source projects. 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 Project: vividus   Source File: MouseActionsTests.java    License: 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 2
Source Project: android_9.0.0_r45   Source File: LiveDataTest.java    License: 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 Project: connector-sdk   Source File: FullTraversalConnectorTest.java    License: 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 4
Source Project: data-highway   Source File: BlockingExecutorTest.java    License: 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 5
Source Project: data-highway   Source File: BlockingExecutorTest.java    License: 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 6
Source Project: connector-sdk   Source File: IndexingApplicationTest.java    License: 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 7
Source Project: java-technology-stack   Source File: ImportSelectorTests.java    License: 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 8
Source Project: android_9.0.0_r45   Source File: LifecycleRegistryTest.java    License: 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 9
@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 10
@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 11
@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 12
Source Project: grpc-nebula-java   Source File: RetriableStreamTest.java    License: 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 13
@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 Project: vividus   Source File: SftpExecutorTests.java    License: 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 15
Source Project: grpc-nebula-java   Source File: RetriableStreamTest.java    License: 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 Project: connector-sdk   Source File: ApplicationTest.java    License: 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 17
@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 Project: vividus   Source File: BatchedEmbedderTests.java    License: 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 19
Source Project: vividus   Source File: HttpRequestExecutorTests.java    License: 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 20
Source Project: vividus   Source File: WindowsActionsTests.java    License: 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 21
Source Project: vividus   Source File: JSchExecutorTests.java    License: 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 22
Source Project: android_9.0.0_r45   Source File: LiveDataTest.java    License: 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 23
Source Project: data-highway   Source File: TowtruckTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void happyPath() throws IOException {
  when(keySupplier.get()).thenReturn(KEY);
  when(outputStreamFactory.apply(KEY)).thenReturn(outputStream);

  underTest.performBackup();

  InOrder inOrder = inOrder(mapper, keySupplier, outputStreamFactory, outputStream);
  inOrder.verify(keySupplier).get();
  inOrder.verify(outputStreamFactory).apply(KEY);
  inOrder.verify(mapper).writeValue(outputStream, store);
  inOrder.verify(outputStream).close();
}
 
Example 24
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example 25
@Test
public void testTransactionWithEnforceReadOnly() throws Exception {
	tm.setEnforceReadOnly(true);

	given(con.getAutoCommit()).willReturn(true);
	Statement stmt = mock(Statement.class);
	given(con.createStatement()).willReturn(stmt);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con, stmt);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(stmt).executeUpdate("SET TRANSACTION READ ONLY");
	ordered.verify(stmt).close();
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).close();
}
 
Example 26
Source Project: vividus   Source File: SshExecutorTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testExecuteCommandsViaSshSuccessfully() throws Exception
{
    ChannelExec channel = mock(ChannelExec.class);
    String errorOutput = "error-output";
    mockErrorStream(errorOutput, channel);
    String commandOutput = "command-output";
    @SuppressWarnings("PMD.CloseResource")
    InputStream channelInputStream = mockChannelInputStream(commandOutput, channel);
    when(channel.isClosed()).thenReturn(Boolean.FALSE).then(invocation ->
    {
        channelInputStream.reset();
        return Boolean.TRUE;
    }).thenReturn(Boolean.TRUE);
    int exitStatus = 1;
    when(channel.getExitStatus()).thenReturn(exitStatus);
    ServerConfiguration serverConfiguration = new ServerConfiguration();
    serverConfiguration.setAgentForwarding(true);
    String commands = "ssh-command";
    SshOutput sshOutput = sshExecutor.executeCommand(serverConfiguration, new Commands(commands), channel);
    assertEquals(commandOutput + commandOutput, sshOutput.getOutputStream());
    assertEquals(errorOutput, sshOutput.getErrorStream());
    assertEquals(exitStatus, sshOutput.getExitStatus());
    InOrder ordered = inOrder(channel);
    ordered.verify(channel).setAgentForwarding(serverConfiguration.isAgentForwarding());
    ordered.verify(channel).setCommand(commands);
    ordered.verify(channel).connect();
    ordered.verify(channel, times(3)).isClosed();
    ordered.verify(channel).getExitStatus();
    ordered.verifyNoMoreInteractions();
}
 
Example 27
Source Project: kafka-helmsman   Source File: FreshnessTrackerTest.java    License: MIT License 5 votes vote down vote up
/**
 * This is a somewhat contrived test case . The first committed offset should be the offset at (0), but this is
 * checking if that isn't the latest (consumer is not up-to-date) but somehow even got something committed. Its
 * strange, but has been seen to happen with old consumers whose offset have fallen off the stream or other,
 * strange cases given the asynchronous nature of the interactions between burrow and kafka.
 */
@Test
public void testSeekToBeginningForFirstOffset() throws Exception {
  Clock clock = Clock.fixed(Instant.now(), Clock.systemDefaultZone().getZone());
  long ts = clock.millis() - 1;
  ConsumerRecords recordsOneMilliBefore = createConsumerRecordsAtTimestamps(ts);
  Consumer kafka = mock(Consumer.class);
  when(kafka.poll(Duration.ofSeconds(2))).thenReturn(recordsOneMilliBefore);

  // this consumer is at the first position (offset 0), so we expect to go back one offset
  FreshnessTracker.ConsumerOffset consumer =
      new FreshnessTracker.ConsumerOffset("cluster", "group", "topic", 1, 0, false);
  FreshnessMetrics metrics = new FreshnessMetrics();
  FreshnessTracker work = new FreshnessTracker(consumer, kafka, metrics);
  work.setClockForTesting(clock);
  work.run();

  InOrder ordered = inOrder(kafka);
  // seeking the committed offset, but go back 1 to actual message
  ordered.verify(kafka).seekToBeginning(Collections.singletonList(new TopicPartition("topic", 1)));
  ordered.verify(kafka).poll(Duration.ofSeconds(2));
  ordered.verifyNoMoreInteractions();

  double noDelta = 0;
  assertEquals("Freshness should be zero for no lag",
      1, metrics.freshness.labels("cluster", "group", "topic", "1").get(), noDelta);
  assertEquals(0, metrics.failed.labels("cluster", "group").get(), 0);
}
 
Example 28
Source Project: android_9.0.0_r45   Source File: LifecycleRegistryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void removeCascade() {
    final TestObserver observer3 = mock(TestObserver.class);
    final TestObserver observer4 = mock(TestObserver.class);

    final TestObserver observer2 = spy(new TestObserver() {
        @Override
        void onStart() {
            mRegistry.removeObserver(this);
        }
    });

    TestObserver observer1 = spy(new TestObserver() {
        @Override
        void onResume() {
            mRegistry.removeObserver(this);
            mRegistry.addObserver(observer2);
            mRegistry.addObserver(observer3);
            mRegistry.addObserver(observer4);
        }
    });
    fullyInitializeRegistry();
    mRegistry.addObserver(observer1);
    InOrder inOrder = inOrder(observer1, observer2, observer3, observer4);
    inOrder.verify(observer1).onCreate();
    inOrder.verify(observer1).onStart();
    inOrder.verify(observer1).onResume();
    inOrder.verify(observer2).onCreate();
    inOrder.verify(observer2).onStart();
    inOrder.verify(observer3).onCreate();
    inOrder.verify(observer3).onStart();
    inOrder.verify(observer4).onCreate();
    inOrder.verify(observer4).onStart();
    inOrder.verify(observer3).onResume();
    inOrder.verify(observer4).onResume();
}
 
Example 29
Source Project: java-technology-stack   Source File: XStreamMarshallerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void marshalSaxResult() throws Exception {
	ContentHandler contentHandler = mock(ContentHandler.class);
	SAXResult result = new SAXResult(contentHandler);
	marshaller.marshal(flight, result);
	InOrder ordered = inOrder(contentHandler);
	ordered.verify(contentHandler).startDocument();
	ordered.verify(contentHandler).startElement(eq(""), eq("flight"), eq("flight"), isA(Attributes.class));
	ordered.verify(contentHandler).startElement(eq(""), eq("flightNumber"), eq("flightNumber"), isA(Attributes.class));
	ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2));
	ordered.verify(contentHandler).endElement("", "flightNumber", "flightNumber");
	ordered.verify(contentHandler).endElement("", "flight", "flight");
	ordered.verify(contentHandler).endDocument();
}
 
Example 30
Source Project: hop   Source File: WorkflowEntryFtpsPutTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * PDI-6868, attempt to set binary mode is after the connection.connect() succeeded.
 *
 * @throws Exception
 */
@Test
public void testBinaryModeSetAfterConnectionSuccess() throws Exception {
  ActionFtpsPut workflow = new ActionFtpsPutCustom();
  FtpsConnection connection = Mockito.mock( FtpsConnection.class );
  InOrder inOrder = Mockito.inOrder( connection );
  workflow.buildFtpsConnection( connection );
  inOrder.verify( connection ).connect();
  inOrder.verify( connection ).setBinaryMode( Mockito.anyBoolean() );
}