本文整理了Java中org.mockito.Mockito.doReturn()
方法的一些代码示例,展示了Mockito.doReturn()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mockito.doReturn()
方法的具体详情如下:
包路径:org.mockito.Mockito
类名称:Mockito
方法名:doReturn
[英]Use doReturn()
in those rare occasions when you cannot use Mockito#when(Object).
Beware that Mockito#when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).
Here are those rare occasions when doReturn() comes handy:
List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing:
doReturn("foo").when(spy).get(0);
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.
See examples in javadoc for Mockito class
[中]在少数无法使用Mockito#when(Object)的情况下使用doReturn()
。
请注意,Mockito#when(Object)总是建议用于存根,因为它是参数类型安全的,可读性更高(尤其是在存根连续调用时)。
以下是doReturn()非常有用的情况:
1.在间谍中监视真实对象并调用真实方法时会产生副作用
List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing:
doReturn("foo").when(spy).get(0);
1.覆盖以前的异常存根:
when(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
以上场景显示了Mockito优雅语法的折衷。但请注意,这种情况非常罕见。间谍活动应该是零星的,覆盖异常存根非常罕见。更不用说,通常重写存根是一种潜在的代码气味,指出了太多的存根。
有关Mockito类,请参见javadoc中的示例
代码示例来源:origin: Netflix/zuul
@Before
public void before() throws Exception
{
MockitoAnnotations.initMocks(this);
loader = spy(new FilterLoader(registry, compiler, filterFactory));
doReturn(TestZuulFilter.class).when(compiler).compile(file);
when(file.getAbsolutePath()).thenReturn("/filters/in/SomeFilter.groovy");
}
代码示例来源:origin: google/guava
@Override
public T apply(Object delegate) {
T mock = mock(forwarderClass, CALLS_REAL_METHODS.get());
try {
T stubber = doReturn(delegate).when(mock);
DELEGATE_METHOD.invoke(stubber);
} catch (Exception e) {
throw new RuntimeException(e);
}
return mock;
}
});
代码示例来源:origin: Netflix/zuul
@Test
public void testGetFilterFromString() throws Exception {
String string = "";
doReturn(TestZuulFilter.class).when(compiler).compile(string, string);
ZuulFilter filter = loader.getFilter(string, string);
assertNotNull(filter);
assertTrue(filter.getClass() == TestZuulFilter.class);
// assertTrue(loader.filterInstanceMapSize() == 1);
}
代码示例来源:origin: neo4j/neo4j
@Test
public void testNotifyListener() throws Exception
{
doReturn( false, true ).when( monitor ).isStopped();
monitor.monitor();
verify( listener ).accept( any(VmPauseInfo.class) );
}
代码示例来源:origin: neo4j/neo4j
@Before
public void setUp()
{
doReturn( jobHandle ).when( jobScheduler ).schedule( any( Group.class ), any( Runnable.class ) );
}
代码示例来源:origin: Alluxio/alluxio
@Test
public void sampleSingle() {
setupLogger(10 * Constants.SECOND_MS);
doReturn(true).when(mBaseLogger).isWarnEnabled();
for (int i = 0; i < 10; i++) {
mSamplingLogger.warn("warning");
}
verify(mBaseLogger, times(1)).warn("warning");
}
代码示例来源:origin: Netflix/zuul
@Test
public void testGetFilterFromString() throws Exception {
String string = "";
doReturn(TestZuulFilter.class).when(compiler).compile(string, string);
ZuulFilter filter = loader.getFilter(string, string);
assertNotNull(filter);
assertTrue(filter.getClass() == TestZuulFilter.class);
// assertTrue(loader.filterInstanceMapSize() == 1);
}
代码示例来源:origin: square/picasso
static Context mockPackageResourceContext() {
Context context = mock(Context.class);
PackageManager pm = mock(PackageManager.class);
Resources res = mock(Resources.class);
doReturn(pm).when(context).getPackageManager();
try {
doReturn(res).when(pm).getResourcesForApplication(RESOURCE_PACKAGE);
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
doReturn(RESOURCE_ID_1).when(res).getIdentifier(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE);
return context;
}
代码示例来源:origin: Netflix/zuul
@Before
public void before() throws Exception
{
MockitoAnnotations.initMocks(this);
loader = spy(new FilterLoader(registry, compiler, filterFactory));
doReturn(TestZuulFilter.class).when(compiler).compile(file);
when(file.getAbsolutePath()).thenReturn("/filters/in/SomeFilter.groovy");
}
代码示例来源:origin: Netflix/eureka
@Override
@Before
public void setUp() throws Exception {
super.setUp();
doReturn(10).when(serverConfig).getWaitTimeInMsWhenSyncEmpty();
doReturn(1).when(serverConfig).getRegistrySyncRetries();
doReturn(1l).when(serverConfig).getRegistrySyncRetryWaitMs();
registry.syncUp();
}
代码示例来源:origin: pentaho/pentaho-kettle
@Test
public void testProcessRow_StreamIsNull() throws Exception {
PGBulkLoader pgBulkLoaderStreamIsNull = mock( PGBulkLoader.class );
doReturn( null ).when( pgBulkLoaderStreamIsNull ).getRow();
PGBulkLoaderMeta meta = mock( PGBulkLoaderMeta.class );
PGBulkLoaderData data = mock( PGBulkLoaderData.class );
assertEquals( false, pgBulkLoaderStreamIsNull.processRow( meta, data ) );
}
代码示例来源:origin: apache/storm
@Test(expected = KeyNotFoundException.class)
public void testKeyNotFoundException() throws Exception {
Map<String, Object> conf = Utils.readStormConfig();
String key1 = "key1";
conf.put(Config.STORM_LOCAL_DIR, "target");
LocalFsBlobStore bs = new LocalFsBlobStore();
LocalFsBlobStore spy = spy(bs);
Mockito.doReturn(true).when(spy).checkForBlobOrDownload(key1);
Mockito.doNothing().when(spy).checkForBlobUpdate(key1);
spy.prepare(conf, null, null, null);
spy.getBlob(key1, null);
}
代码示例来源:origin: neo4j/neo4j
ReadableTransactionState build()
{
final ReadableTransactionState mock = Mockito.mock( ReadableTransactionState.class );
doReturn( new UnmodifiableMap<>( updates ) ).when( mock ).getIndexUpdates( any( SchemaDescriptor.class ) );
final TreeMap<ValueTuple, MutableLongDiffSetsImpl> sortedMap = new TreeMap<>( ValueTuple.COMPARATOR );
sortedMap.putAll( updates );
doReturn( sortedMap ).when( mock ).getSortedIndexUpdates( any( SchemaDescriptor.class ) );
return mock;
}
}
代码示例来源:origin: Alluxio/alluxio
@Test
public void sampleMultiple() {
setupLogger(10 * Constants.SECOND_MS);
doReturn(true).when(mBaseLogger).isWarnEnabled();
for (int i = 0; i < 10; i++) {
mSamplingLogger.warn("warning1");
mSamplingLogger.warn("warning2");
}
verify(mBaseLogger, times(1)).warn("warning1");
verify(mBaseLogger, times(1)).warn("warning2");
}
代码示例来源:origin: gocd/gocd
@Test
public void shouldGetCurrentLogDirectoryByLookingAtFileAppenderOfRootLogger() throws Exception {
if (WINDOWS.satisfy()) {
return;
}
FileAppender fileAppender = new FileAppender();
fileAppender.setFile("/var/log/go-server/go-server.log");
DefaultPluginLoggingService service = Mockito.spy(new DefaultPluginLoggingService(systemEnvironment));
doReturn(fileAppender).when(service).getGoServerLogFileAppender();
String currentLogDirectory = service.getCurrentLogDirectory();
assertThat(currentLogDirectory, is("/var/log/go-server"));
}
代码示例来源:origin: apache/hbase
@Test
public void testRequestQuoterWithNull() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.doReturn(null).when(request).getParameterValues("dummy");
RequestQuoter requestQuoter = new RequestQuoter(request);
String[] parameterValues = requestQuoter.getParameterValues("dummy");
Assert.assertEquals("It should return null "
+ "when there are no values for the parameter", null, parameterValues);
}
代码示例来源:origin: pentaho/pentaho-kettle
@Test
public void testWriteFile() throws Exception {
String path = getClass().getResource( "repositories.xml" ).getPath().replace( "repositories.xml", "new-repositories.xml" );
doReturn( path ).when( repoMeta ).getKettleUserRepositoriesFile();
repoMeta.writeData();
InputStream resourceAsStream = getClass().getResourceAsStream( "new-repositories.xml" );
assertEquals(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Const.CR
+ "<repositories>" + Const.CR
+ " </repositories>" + Const.CR, IOUtils.toString( resourceAsStream ) );
new File( path ).delete();
}
代码示例来源:origin: pentaho/pentaho-kettle
@Test
public void getLocationFrom() {
HttpPost postMethod = mock( HttpPost.class );
Header locationHeader = new BasicHeader( LOCATION_HEADER, TEST_URL );
doReturn( locationHeader ).when( postMethod ).getFirstHeader( LOCATION_HEADER );
assertEquals( TEST_URL, WebService.getLocationFrom( postMethod ) );
}
代码示例来源:origin: pentaho/pentaho-kettle
@Test
public void testNewTransformationsWithContainerObjectId() throws Exception {
TransMeta meta = mock( TransMeta.class );
doReturn( new String[] { "X", "Y", "Z" } ).when( meta ).listVariables();
doReturn( new String[] { "A", "B", "C" } ).when( meta ).listParameters();
doReturn( "XYZ" ).when( meta ).getVariable( anyString() );
doReturn( "" ).when( meta ).getParameterDescription( anyString() );
doReturn( "" ).when( meta ).getParameterDefault( anyString() );
doReturn( "ABC" ).when( meta ).getParameterValue( anyString() );
String carteId = UUID.randomUUID().toString();
doReturn( carteId ).when( meta ).getContainerObjectId();
Trans trans = new Trans( meta );
assertEquals( carteId, trans.getContainerObjectId() );
}
代码示例来源:origin: gocd/gocd
@Test
public void shouldReturnSdkCommand() throws Exception {
TfsCommand expectedTfsCommand = mock(TfsCommand.class);
TfsCommandFactory spyCommandFactory = spy(tfsCommandFactory);
TfsSDKCommandBuilder commandBuilder = mock(TfsSDKCommandBuilder.class);
doReturn(commandBuilder).when(spyCommandFactory).getSDKBuilder();
when(commandBuilder.buildTFSSDKCommand("fingerprint", URL, DOMAIN, USERNAME, PASSWORD, computedWorkspaceName, PROJECT_PATH)).thenReturn(expectedTfsCommand);
TfsCommand actualTfsCommand = spyCommandFactory.create(executionContext, URL, DOMAIN, USERNAME, PASSWORD, "fingerprint", PROJECT_PATH);
assertThat(actualTfsCommand, is(expectedTfsCommand));
verify(commandBuilder).buildTFSSDKCommand("fingerprint", URL, DOMAIN, USERNAME, PASSWORD, computedWorkspaceName, PROJECT_PATH);
}
内容来源于网络,如有侵权,请联系作者删除!