本文整理了Java中org.mockito.Mockito.timeout()
方法的一些代码示例,展示了Mockito.timeout()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mockito.timeout()
方法的具体详情如下:
包路径:org.mockito.Mockito
类名称:Mockito
方法名:timeout
[英]Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent conditions.
It feels this feature should be used rarely - figure out a better way of testing your multi-threaded system
Not yet implemented to work with InOrder verification.
//passes when someMethod() is called within given time span
verify(mock, timeout(100)).someMethod();
//above is an alias to:
verify(mock, timeout(100).times(1)).someMethod();
//passes when someMethod() is called *exactly* 2 times within given time span
verify(mock, timeout(100).times(2)).someMethod();
//passes when someMethod() is called *at least* 2 times within given time span
verify(mock, timeout(100).atLeast(2)).someMethod();
//verifies someMethod() within given time span using given verification mode
//useful only if you have your own custom verification modes.
verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
See examples in javadoc for Mockito class
[中]允许使用超时进行验证。它使验证等待指定的时间段以进行所需的交互,而不是在尚未发生的情况下立即失败。可能有助于在并发条件下进行测试。
它觉得这个功能应该很少使用-找出一个更好的方法来测试你的多线程系统
尚未实现以使用顺序验证。
//passes when someMethod() is called within given time span
verify(mock, timeout(100)).someMethod();
//above is an alias to:
verify(mock, timeout(100).times(1)).someMethod();
//passes when someMethod() is called *exactly* 2 times within given time span
verify(mock, timeout(100).times(2)).someMethod();
//passes when someMethod() is called *at least* 2 times within given time span
verify(mock, timeout(100).atLeast(2)).someMethod();
//verifies someMethod() within given time span using given verification mode
//useful only if you have your own custom verification modes.
verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
请参阅javadoc中Mockito类的示例
代码示例来源:origin: spotify/helios
@Test
public void test() throws Exception {
startDefaultMaster("--service-registry=" + registryAddress);
verify(registrar, timeout((int) SECONDS.toMillis(LONG_WAIT_SECONDS)))
.register(registrationCaptor.capture());
final ServiceRegistration registration = registrationCaptor.getValue();
final ServiceRegistration.Endpoint endpoint = getOnlyElement(registration.getEndpoints());
assertEquals("http", endpoint.getProtocol());
assertEquals("helios", endpoint.getName());
assertEquals(masterPort(), endpoint.getPort());
}
}
代码示例来源:origin: cloudfoundry/uaa
@Test
public void test_invalid_password_match() throws Exception {
PasswordConfirmationException pe = new PasswordConfirmationException(messageCode, email);
BadCredentialsException be = new BadCredentialsException("", pe);
entryPoint.commence(request, response, be);
verify(request, times(1)).getRequestDispatcher(eq("/reset_password"));
verify(request, times(1)).setAttribute(eq("message_code"), eq(messageCode));
verify(requestDispatcher, timeout(1)).forward(any(HttpServletRequest.class), same(response));
verify(response, times(1)).setStatus(eq(HttpStatus.UNPROCESSABLE_ENTITY.value()));
}
代码示例来源:origin: cloudfoundry/uaa
@Test
public void test_when_invalid_password_exception() throws Exception {
InvalidPasswordException pe = new InvalidPasswordException(Arrays.asList("one","two"));
BadCredentialsException be = new BadCredentialsException("", pe);
entryPoint.commence(request, response, be);
verify(request, times(1)).getRequestDispatcher(eq("/reset_password"));
verify(request, times(1)).setAttribute(eq("message"), eq(pe.getMessagesAsOneString()));
verify(requestDispatcher, timeout(1)).forward(any(HttpServletRequest.class), same(response));
verify(response, times(1)).setStatus(eq(HttpStatus.UNPROCESSABLE_ENTITY.value()));
}
代码示例来源:origin: kaaproject/kaa
@Override
public void run() {
Mockito.verify(channel, Mockito.timeout(100).times(1)).setServer(bootststrapServers.get(TransportProtocolIdConstants.HTTP_TRANSPORT_ID).get(1));
}
});
代码示例来源:origin: cloudfoundry/uaa
@Test
public void test_when_uaa_exception() throws Exception {
UaaException e = new UaaException(messageCode);
InternalAuthenticationServiceException be = new InternalAuthenticationServiceException("", e);
entryPoint.commence(request, response, be);
verify(request, times(1)).getRequestDispatcher(eq("/forgot_password"));
verify(request, times(1)).setAttribute(eq("message_code"), eq("bad_code"));
verify(requestDispatcher, timeout(1)).forward(any(HttpServletRequest.class), same(response));
verify(response, times(1)).setStatus(eq(HttpStatus.UNPROCESSABLE_ENTITY.value()));
}
代码示例来源:origin: SonarSource/sonarqube
@Test
public void shouldLogEvery10Minutes() {
setUpMocks();
// Emulate 2 notifications in DB
when(manager.getFromQueue()).thenReturn(notification).thenReturn(notification).thenReturn(null);
when(manager.count()).thenReturn(1L).thenReturn(0L);
underTest = spy(underTest);
// Emulate processing of each notification take 10 min to have a log each time
when(underTest.now()).thenReturn(0L).thenReturn(10 * 60 * 1000 + 1L).thenReturn(20 * 60 * 1000 + 2L);
underTest.start();
verify(underTest, timeout(200)).log(1, 1, 10);
verify(underTest, timeout(200)).log(2, 0, 20);
underTest.stop();
}
代码示例来源:origin: kaaproject/kaa
@Override
public void run() {
Mockito.verify(accessPointIdResolutionSpy, Mockito.timeout(BOOTSTRAP_RETRY_PERIOD * 2).times(1)).setCurResolution(null);
}
}).start();
代码示例来源:origin: kaaproject/kaa
@Test
public void failureOnResumeTest() {
client.start();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStarted();
client.pause();
Mockito.verify(stateListener, Mockito.timeout(1000)).onPaused();
KaaInternalChannelManager channelManager = Mockito.mock(KaaInternalChannelManager.class);
Mockito.doThrow(new RuntimeException()).when(channelManager).resume();
ReflectionTestUtils.setField(client, "channelManager", channelManager);
client.resume();
Mockito.verify(stateListener, Mockito.timeout(1000)).onResumeFailure(Mockito.any(KaaException.class));
}
代码示例来源:origin: gocd/gocd
@Test
public void shouldReadOutputOfAGiveStream() throws Exception {
StringBufferInputStream in = new StringBufferInputStream("Lorem ipsum dolor sit amet, consectetur adipisicing elit, \n"
+ "used do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n "
+ "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi \n"
+ "ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit \n"
+ "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \n "
+ "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui \n"
+ "officia deserunt mollit anim id est laborum.");
doNothing().when(safeOutputStreamConsumer).stdOutput(anyString());
console.readOutputOf(in);
verify(safeOutputStreamConsumer, timeout(10000).times(7)).stdOutput(anyString());
}
代码示例来源:origin: gocd/gocd
@Test
public void shouldReadErrorOfAGiveStream() throws Exception {
StringBufferInputStream in = new StringBufferInputStream("Lorem ipsum dolor sit amet, consectetur adipisicing elit, \n"
+ "used do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n "
+ "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi \n"
+ "ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit \n"
+ "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \n "
+ "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui \n"
+ "officia deserunt mollit anim id est laborum.");
doNothing().when(safeOutputStreamConsumer).errOutput(anyString());
console.readErrorOf(in);
verify(safeOutputStreamConsumer, timeout(10000).times(7)).errOutput(anyString());
}
代码示例来源:origin: kaaproject/kaa
@Test
public void basicLifeCycleTest() throws Exception {
client.start();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStarted();
Mockito.verify(bsManagerMock).receiveOperationsServerList();
client.pause();
Mockito.verify(stateListener, Mockito.timeout(1000)).onPaused();
client.resume();
Mockito.verify(stateListener, Mockito.timeout(1000)).onResume();
client.stop();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStopped();
}
代码示例来源:origin: SonarSource/sonarqube
@Test
public void shouldNotStopWhenException() {
setUpMocks();
when(manager.getFromQueue()).thenThrow(new RuntimeException("Unexpected exception")).thenReturn(notification).thenReturn(null);
doAnswer(addUser(ASSIGNEE_SIMON, emailChannel)).when(commentOnIssueAssignedToMe).dispatch(same(notification), any(NotificationDispatcher.Context.class));
doAnswer(addUser(CREATOR_SIMON, emailChannel)).when(commentOnIssueCreatedByMe).dispatch(same(notification), any(NotificationDispatcher.Context.class));
underTest.start();
verify(emailChannel, timeout(2000)).deliver(notification, ASSIGNEE_SIMON);
underTest.stop();
verify(gtalkChannel, never()).deliver(notification, ASSIGNEE_SIMON);
}
代码示例来源:origin: kaaproject/kaa
@Test
public void failureOnStartTest() throws TransportException {
Mockito.doThrow(new KaaRuntimeException(new Exception("cause"))).when(bsManagerMock).receiveOperationsServerList();
client.start();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStartFailure(Mockito.any(KaaException.class));
}
代码示例来源:origin: kaaproject/kaa
@Test
public void basicStartBSFailureTest() throws Exception {
Mockito.doThrow(new TransportException("mock")).when(bsManagerMock).receiveOperationsServerList();
client.start();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStartFailure(Mockito.any(KaaException.class));
Mockito.verify(bsManagerMock).receiveOperationsServerList();
client.stop();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStopped();
}
代码示例来源:origin: kaaproject/kaa
@Test
public void failureOnStopTest() {
client.start();
AbstractLogCollector logCollector = Mockito.mock(AbstractLogCollector.class);
Mockito.doThrow(new RuntimeException()).when(logCollector).stop();
ReflectionTestUtils.setField(client, "logCollector", logCollector);
client.stop();
Mockito.verify(stateListener, Mockito.timeout(1000)).onStopFailure(Mockito.any(KaaException.class));
}
代码示例来源:origin: Netflix/eureka
@Test
public void testBatchProcessingWithTransientError() throws Exception {
taskExecutors = TaskExecutors.batchExecutors("TEST", 1, processor, acceptorExecutor);
List<TaskHolder<Integer, ProcessingResult>> taskHolderBatch = asList(transientErrorTaskHolder(1), transientErrorTaskHolder(2));
taskBatchQueue.add(taskHolderBatch);
// Verify that transient task is be re-scheduled
processor.expectTransientErrors(2);
verify(acceptorExecutor, timeout(500).times(1)).reprocess(taskHolderBatch, ProcessingResult.TransientError);
}
代码示例来源:origin: kaaproject/kaa
@Test
public void failureOnPauseTest() {
client.start();
KaaClientState clientState = Mockito.mock(KaaClientState.class);
Mockito.doThrow(new RuntimeException()).when(clientState).persist();
ReflectionTestUtils.setField(client, "kaaClientState", clientState);
client.pause();
Mockito.verify(stateListener, Mockito.timeout(1000)).onPauseFailure(Mockito.any(KaaException.class));
}
代码示例来源:origin: real-logic/aeron
@Test
public void shouldCatchErrorOnAddressAlreadyInUseForSubscriptions()
{
final Subscription subscriptionA = clientA.addSubscription(URI, STREAM_ID);
while (subscriptionA.channelStatus() == ChannelEndpointStatus.INITIALIZING)
{
SystemTest.checkInterruptedStatus();
Thread.yield();
}
assertThat(subscriptionA.channelStatus(), is(ChannelEndpointStatus.ACTIVE));
final Subscription subscriptionB = clientB.addSubscription(URI, STREAM_ID);
final ArgumentCaptor<Throwable> captor = ArgumentCaptor.forClass(Throwable.class);
verify(errorHandlerClientB, timeout(5000)).onError(captor.capture());
assertThat(captor.getValue(), instanceOf(ChannelEndpointException.class));
final ChannelEndpointException channelEndpointException = (ChannelEndpointException)captor.getValue();
final long status = clientB.countersReader().getCounterValue(channelEndpointException.statusIndicatorId());
assertThat(status, is(ChannelEndpointStatus.ERRORED));
assertThat(errorCounter.get(), greaterThan(0));
assertThat(subscriptionB.channelStatusId(), is(channelEndpointException.statusIndicatorId()));
assertThat(subscriptionA.channelStatus(), is(ChannelEndpointStatus.ACTIVE));
}
代码示例来源:origin: Netflix/eureka
@Test
public void testSingleItemProcessingWithTransientError() throws Exception {
taskExecutors = TaskExecutors.singleItemExecutors("TEST", 1, processor, acceptorExecutor);
TaskHolder<Integer, ProcessingResult> taskHolder = transientErrorTaskHolder(1);
taskQueue.add(taskHolder);
// Verify that transient task is be re-scheduled
processor.expectTransientErrors(1);
verify(acceptorExecutor, timeout(500).times(1)).reprocess(taskHolder, ProcessingResult.TransientError);
}
代码示例来源:origin: real-logic/aeron
@Test(timeout = 2000)
public void shouldBeAbleToAddCounter()
{
launch();
final Counter counter = clientA.addCounter(
COUNTER_TYPE_ID,
null,
0,
0,
labelBuffer,
0,
COUNTER_LABEL.length());
assertFalse(counter.isClosed());
verify(availableCounterHandlerClientA, timeout(1000))
.onAvailableCounter(any(CountersReader.class), eq(counter.registrationId()), eq(counter.id()));
verify(availableCounterHandlerClientB, timeout(1000))
.onAvailableCounter(any(CountersReader.class), eq(counter.registrationId()), eq(counter.id()));
}
内容来源于网络,如有侵权,请联系作者删除!