本文整理了Java中org.mockito.Mockito.reset()
方法的一些代码示例,展示了Mockito.reset()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mockito.reset()
方法的具体详情如下:
包路径:org.mockito.Mockito
类名称:Mockito
方法名:reset
[英]Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. Normally, you don't need to reset your mocks, just create new mocks for each test method.
Instead of #reset()
please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell is reset()
in the middle of the test method. This probably means you're testing too much. Follow the whisper of your test methods: "Please keep us small & focused on single behavior". There are several threads about it on mockito mailing list.
The only reason we added reset()
method is to make it possible to work with container-injected mocks. See issue 55 (here) or FAQ (here).
Don't harm yourself.reset()
in the middle of the test method is a code smell (you're probably testing too much).
List mock = mock(List.class);
when(mock.size()).thenReturn(10);
mock.add(1);
reset(mock);
//at this point the mock forgot any interactions & stubbing
[中]聪明的Mockito用户很少使用此功能,因为他们知道这可能是测试不好的迹象。通常,您不需要重置模拟,只需为每个测试方法创建新的模拟即可。
而不是[ [ 0美元] ]请考虑编写简单,小而集中的测试方法,长,超指定的测试。在测试方法的中期,第一个潜在的代码气味是[(1美元)]。这可能意味着你测试得太多了。遵循你的测试方法:“请让我们保持小规模,专注于单一行为”。mockito邮件列表上有几个关于它的帖子。
我们添加reset()
方法的唯一原因是可以使用容器注入的mock。见第55期({$0$})或常见问题解答({$1$})。
不要伤害你自己。在测试方法的中间([$$$])是代码气味(您可能测试太多)。
List mock = mock(List.class);
when(mock.size()).thenReturn(10);
mock.add(1);
reset(mock);
//at this point the mock forgot any interactions & stubbing
代码示例来源:origin: bumptech/glide
@Test
public void testDoesNotPutNullBitmapAcquiredFromPool() {
reset(pool);
when(pool.get(anyInt(), anyInt(), any(Bitmap.Config.class))).thenReturn(null);
centerCrop.transform(context, resource, 100, 100);
verify(pool, never()).put(any(Bitmap.class));
}
代码示例来源:origin: neo4j/neo4j
private void resetOutsideWorldMock()
{
reset( out );
when( out.fileSystem() ).thenReturn( fileSystem );
}
}
代码示例来源:origin: apache/storm
void verifyAllMessagesCommitted(long messageCount) {
verify(consumerSpy).commitSync(commitCapture.capture());
final Map<TopicPartition, OffsetAndMetadata> commits = commitCapture.getValue();
assertThat("Expected commits for only one topic partition", commits.entrySet().size(), is(1));
OffsetAndMetadata offset = commits.entrySet().iterator().next().getValue();
assertThat("Expected committed offset to cover all emitted messages", offset.offset(), is(messageCount));
reset(consumerSpy);
}
}
代码示例来源:origin: neo4j/neo4j
@Test
public void tryCheckPointShouldWaitTheCurrentCheckPointingToCompleteNoRunCheckPointButUseTheTxIdOfTheEarlierRun()
throws Throwable
{
// Given
Lock lock = mock( Lock.class );
final CheckPointerImpl checkPointing = checkPointer( mutex( lock ) );
mockTxIdStore();
checkPointing.forceCheckPoint( INFO );
verify( appender ).checkPoint( eq( logPosition ), any( LogCheckPointEvent.class ) );
reset( appender );
checkPointing.tryCheckPoint( INFO );
verifyNoMoreInteractions( appender );
}
代码示例来源:origin: neo4j/neo4j
@Test
public void transferMigratedIndexesToStoreDirectory() throws IOException
{
ExplicitIndexProvider indexProviders = getExplicitIndexProvider();
ExplicitIndexMigrator indexMigrator = new TestExplicitIndexMigrator( fs, indexProviders, logProvider, true );
indexMigrator.migrate( storeLayout, migrationLayout, progressMonitor, StandardV2_3.STORE_VERSION,
StandardV3_0.STORE_VERSION );
reset( fs );
indexMigrator.moveMigratedFiles( migrationLayout, storeLayout, "any", "any" );
verify( fs ).deleteRecursively( originalIndexStore );
verify( fs ).moveToDirectory( migratedIndexStore, storeLayout.databaseDirectory() );
}
代码示例来源:origin: ehcache/ehcache3
@Test
public void testFailingTransitionGoesToLowestStatus() throws Exception {
final LifeCycled mock = mock(LifeCycled.class);
InternalCache ehcache = getCache(mock(Store.class));
doThrow(new Exception()).when(mock).init();
ehcache.addHook(mock);
try {
ehcache.init();
fail();
} catch (StateTransitionException e) {
assertThat(ehcache.getStatus(), is(Status.UNINITIALIZED));
}
reset(mock);
ehcache.init();
assertThat(ehcache.getStatus(), is(Status.AVAILABLE));
ehcache.close();
}
代码示例来源:origin: neo4j/neo4j
@Test
public void shouldResumeTransactionWhenExecutingStatementsOnSecondRequest() throws Exception
TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction( explicit, AUTH_DISABLED, -1);
TransactionRegistry registry = mock( TransactionRegistry.class );
QueryExecutionEngine executionEngine = mock( QueryExecutionEngine.class );
TransactionalContext transactionalContext = prepareKernelWithQuerySession( kernel );
when( registry.begin( any( TransactionHandle.class ) ) ).thenReturn( 1337L );
TransactionHandle handle = getTransactionHandle( kernel, executionEngine, registry );
ExecutionResultSerializer output = mock( ExecutionResultSerializer.class );
mock( HttpServletRequest.class ) );
reset( transactionContext, registry, executionEngine, output );
Result executionResult = mock( Result.class );
when( executionEngine.executeQuery( "query", NO_PARAMS, transactionalContext )
).thenReturn( executionResult );
代码示例来源:origin: SonarSource/sonarqube
@Test
public void onServerStart_has_no_effect_if_called_twice_to_support_medium_test_doing_startup_tasks_multiple_times() {
underTest.onServerStart(server);
reset(processingScheduler, cleaningScheduler);
underTest.onServerStart(server);
verifyZeroInteractions(processingScheduler, cleaningScheduler);
}
}
代码示例来源:origin: SonarSource/sonarqube
@Test
public void execute_fails_with_exception_thrown_by_interrupter() throws Throwable {
executeFailsWithExceptionThrownByInterrupter();
reset(computationStep1, computationStep2, computationStep3, taskInterrupter);
runInOtherThread(this::executeFailsWithExceptionThrownByInterrupter);
}
代码示例来源:origin: org.mockito/mockito-core
@Override
protected boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {
FieldReader fieldReader = new FieldReader(fieldOwner, field);
// TODO refoctor : code duplicated in SpyAnnotationEngine
if(!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) {
try {
Object instance = fieldReader.read();
if (MockUtil.isMock(instance)) {
// A. instance has been spied earlier
// B. protect against multiple use of MockitoAnnotations.initMocks()
Mockito.reset(instance);
} else {
Object mock = Mockito.mock(instance.getClass(), withSettings()
.spiedInstance(instance)
.defaultAnswer(Mockito.CALLS_REAL_METHODS)
.name(field.getName()));
setField(fieldOwner, field, mock);
}
} catch (Exception e) {
throw new MockitoException("Problems initiating spied field " + field.getName(), e);
}
}
return false;
}
}
代码示例来源:origin: ben-manes/caffeine
@Test
public void scheduleDrainBuffers() {
Executor executor = Mockito.mock(Executor.class);
BoundedLocalCache<?, ?> cache = new BoundedLocalCache<Object, Object>(
Caffeine.newBuilder().executor(executor), /* loader */ null, /* async */ false) {};
Map<Integer, Integer> transitions = ImmutableMap.of(
IDLE, PROCESSING_TO_IDLE,
REQUIRED, PROCESSING_TO_IDLE,
PROCESSING_TO_IDLE, PROCESSING_TO_IDLE,
PROCESSING_TO_REQUIRED, PROCESSING_TO_REQUIRED);
transitions.forEach((start, end) -> {
cache.drainStatus = start;
cache.scheduleDrainBuffers();
assertThat(cache.drainStatus, is(end));
if (!start.equals(end)) {
Mockito.verify(executor).execute(any());
Mockito.reset(executor);
}
});
}
代码示例来源:origin: SonarSource/sonarqube
private void verifyNoRedirection(String requestUrl, @Nullable String queryString) throws IOException, ServletException {
when(request.getRequestURI()).thenReturn(requestUrl);
when(request.getQueryString()).thenReturn(queryString);
when(request.getParameter(anyString())).thenReturn(null);
underTest.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
verifyZeroInteractions(response);
reset(response, chain);
}
}
代码示例来源:origin: ehcache/ehcache3
@Test
@SuppressWarnings("unchecked")
public void testSimpleRemove2ArgsWithLoaderAndWriter_existsInStore() throws Exception {
testCache.put(1, "un");
reset(cacheLoaderWriter);
assertThat(testCache.remove(1, "un"), is(true));
verify(cacheLoaderWriter, times(1)).delete(eq(1));
verifyNoMoreInteractions(cacheLoaderWriter);
}
代码示例来源:origin: cloudfoundry/uaa
@Test
public void create_or_get_tries_get_first() throws Exception {
reset(dao);
dao.createOrGet(new ScimGroup("openid"), IdentityZone.getUaa().getId());
verify(dao, times(1)).getByName("openid", IdentityZone.getUaa().getId());
verify(dao, never()).createAndIgnoreDuplicate(anyString(), anyString());
}
代码示例来源:origin: org.apache.logging.log4j/log4j-core
@Test
public void testBuffering01() throws Exception {
setUp("name", 0);
final LogEvent event1 = mock(LogEvent.class);
final LogEvent event2 = mock(LogEvent.class);
final LogEvent event3 = mock(LogEvent.class);
manager.startup();
then(manager).should().startupInternal();
reset(manager);
manager.write(event1, null);
then(manager).should().connectAndStart();
then(manager).should().writeInternal(same(event1), (Serializable) isNull());
then(manager).should().commitAndClose();
reset(manager);
manager.write(event2, null);
then(manager).should().connectAndStart();
then(manager).should().writeInternal(same(event2), (Serializable) isNull());
then(manager).should().commitAndClose();
reset(manager);
manager.write(event3, null);
then(manager).should().connectAndStart();
then(manager).should().writeInternal(same(event3), (Serializable) isNull());
then(manager).should().commitAndClose();
then(manager).shouldHaveNoMoreInteractions();
}
代码示例来源:origin: SonarSource/sonarqube
@Test
public void execute_calls_interrupter_with_current_thread_before_each_step() throws Throwable {
executeCallsInterrupterWithCurrentThreadBeforeEachStep();
reset(computationStep1, computationStep2, computationStep3, taskInterrupter);
runInOtherThread(this::executeCallsInterrupterWithCurrentThreadBeforeEachStep);
}
代码示例来源:origin: neo4j/neo4j
private void resetOutsideWorldMock()
{
reset(out);
when( out.fileSystem() ).thenReturn( fileSystem );
}
}
代码示例来源:origin: google/j2objc
Mockito.reset(instance);
} else {
field.setAccessible(true);
field.set(testInstance, Mockito.mock(instance.getClass(), withSettings()
.spiedInstance(instance)
.defaultAnswer(Mockito.CALLS_REAL_METHODS)
代码示例来源:origin: spring-projects/spring-framework
private Message<String> startSession(String id) {
this.messageHandler.start();
Message<String> connectMessage = createConnectMessage(id, new TestPrincipal("joe"), null);
this.messageHandler.setTaskScheduler(this.taskScheduler);
this.messageHandler.handleMessage(connectMessage);
verify(this.clientOutChannel, times(1)).send(this.messageCaptor.capture());
reset(this.clientOutChannel);
return connectMessage;
}
代码示例来源:origin: SonarSource/sonarqube
private void verifyRedirection(String requestUrl, @Nullable String queryString, String expectedRedirection) throws Exception {
when(request.getRequestURI()).thenReturn(requestUrl);
when(request.getQueryString()).thenReturn(queryString);
underTest.doFilter(request, response, chain);
verify(response).sendRedirect(expectedRedirection);
verifyZeroInteractions(chain);
reset(response, chain);
}
内容来源于网络,如有侵权,请联系作者删除!