org.mockito.Mockito.spy()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(416)

本文整理了Java中org.mockito.Mockito.spy()方法的一些代码示例,展示了Mockito.spy()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mockito.spy()方法的具体详情如下:
包路径:org.mockito.Mockito
类名称:Mockito
方法名:spy

Mockito.spy介绍

[英]Please refer to the documentation of #spy(Object). Overusing spies hints at code design smells.

This method, in contrast to the original #spy(Object), creates a spy based on class instead of an object. Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object. This is particularly useful for spying on abstract classes because they cannot be instantiated. See also MockSettings#useConstructor(Object...).

Examples:

SomeAbstract spy = spy(SomeAbstract.class); 
//Robust API, via settings builder: 
OtherAbstract spy = mock(OtherAbstract.class, withSettings() 
.useConstructor().defaultAnswer(CALLS_REAL_METHODS)); 
//Mocking a non-static inner abstract class: 
InnerAbstract spy = mock(InnerAbstract.class, withSettings() 
.useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));

[中]请参阅#spy(Object)的文档。过度使用间谍暗示了代码设计的味道。
与原始的#spy(Object)不同,该方法基于类而不是对象创建一个spy。有时,基于类创建spy并避免提供spied对象的实例更方便。这对于监视抽象类尤其有用,因为它们无法实例化。另请参见MockSettings#useConstructor(对象…)。
示例:

SomeAbstract spy = spy(SomeAbstract.class); 
//Robust API, via settings builder: 
OtherAbstract spy = mock(OtherAbstract.class, withSettings() 
.useConstructor().defaultAnswer(CALLS_REAL_METHODS)); 
//Mocking a non-static inner abstract class: 
InnerAbstract spy = mock(InnerAbstract.class, withSettings() 
.useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));

代码示例

代码示例来源: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/zuul

@Test
  public void testFileManagerInit() throws Exception
  {
    FilterFileManagerConfig config = new FilterFileManagerConfig(new String[]{"test", "test1"}, new String[]{"com.netflix.blah.SomeFilter"}, 1);
    FilterFileManager manager = new FilterFileManager(config, filterLoader);
    manager = spy(manager);
    doNothing().when(manager).manageFiles();
    manager.init();
    verify(manager, atLeast(1)).manageFiles();
    verify(manager, times(1)).startPoller();
    assertNotNull(manager.poller);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void importSelectors() {
  DefaultListableBeanFactory beanFactory = spy(new DefaultListableBeanFactory());
  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(beanFactory);
  context.register(Config.class);
  context.refresh();
  context.getBean(Config.class);
  InOrder ordered = inOrder(beanFactory);
  ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any());
  ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
  ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
  ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void allowedOptionsIncludesPatchMethod() throws Exception {
  MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "OPTIONS", "/foo");
  MockHttpServletResponse response = spy(new MockHttpServletResponse());
  DispatcherServlet servlet = new DispatcherServlet();
  servlet.setDispatchOptionsRequest(false);
  servlet.service(request, response);
  verify(response, never()).getHeader(anyString()); // SPR-10341
  assertThat(response.getHeader("Allow"), equalTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"));
}

代码示例来源:origin: bumptech/glide

@SuppressWarnings("deprecation")
@Test
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void testDoesNotThrowIfAskedToGetManagerForFragmentPreJellyBeanMr1() {
 Util.setSdkVersionInt(Build.VERSION_CODES.JELLY_BEAN);
 Activity activity = Robolectric.buildActivity(Activity.class).create().start().resume().get();
 android.app.Fragment fragment = new android.app.Fragment();
 activity.getFragmentManager().beginTransaction().add(fragment, "test").commit();
 android.app.Fragment spyFragment = Mockito.spy(fragment);
 when(spyFragment.getChildFragmentManager()).thenThrow(new NoSuchMethodError());
 assertNotNull(retriever.get(spyFragment));
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldCramMultipleDecoratorsIntoOne()
{
  // GIVEN
  Decorator decorator1 = spy( new IdentityDecorator() );
  Decorator decorator2 = spy( new IdentityDecorator() );
  Decorator multi = decorators( decorator1, decorator2 );
  // WHEN
  InputEntityVisitor node = mock( InputEntityVisitor.class );
  multi.apply( node );
  // THEN
  InOrder order = inOrder( decorator1, decorator2 );
  order.verify( decorator1, times( 1 ) ).apply( node );
  order.verify( decorator2, times( 1 ) ).apply( node );
  order.verifyNoMoreInteractions();
}

代码示例来源: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: square/picasso

static Action mockAction(Request request, final Object target, String tag) {
 Action action = spy(new Action(mockPicasso(), request) {
  @Override void complete(RequestHandler.Result result) {
  }
  @Override void error(Exception e) {
  }
  @Override Object getTarget() {
   return target;
  }
 });
 when(action.getTag()).thenReturn(tag != null ? tag : action);
 return action;
}

代码示例来源:origin: checkstyle/checkstyle

private static void verifyOutput(String expected, AuditEvent... events) throws IOException {
    final OutputStream out = spy(new ByteArrayOutputStream());
    final XpathFileGeneratorAuditListener listener =
        new XpathFileGeneratorAuditListener(out, AutomaticBean.OutputStreamOptions.CLOSE);

    for (AuditEvent event : events) {
      listener.addError(event);
    }

    listener.auditFinished(null);

    verify(out, times(1)).flush();
    verify(out, times(1)).close();

    final String actual = out.toString();
    assertEquals("Invalid suppressions file content", expected, actual);
  }
}

代码示例来源:origin: gocd/gocd

private AgentBootstrapper stubJVMExit(AgentBootstrapper bootstrapper) {
  AgentBootstrapper spy = spy(bootstrapper);
  doNothing().when(spy).jvmExit(anyInt());
  return spy;
}

代码示例来源:origin: gocd/gocd

@Test
public void shouldClearWorkingDirectoryBeforeCheckingOut() throws Exception {
  File workingDirectory = mock(File.class);
  when(workingDirectory.exists()).thenReturn(true);
  TfsSDKCommand spy = spy(tfsCommand);
  doNothing().when(spy).initializeWorkspace(workingDirectory);
  doNothing().when(spy).retrieveFiles(workingDirectory, null);
  spy.checkout(workingDirectory, null);
  verify(workingDirectory).exists();
}

代码示例来源:origin: gocd/gocd

@Test
public void shouldCheckConnection() {
  TestSubprocessExecutionContext execCtx = new TestSubprocessExecutionContext();
  TfsCommand tfsCommand = mock(TfsCommand.class);
  doNothing().when(tfsCommand).checkConnection();
  TfsMaterial spy = spy(tfsMaterialFirstCollectionFirstProject);
  doReturn(tfsCommand).when(spy).tfs(execCtx);
  assertThat(spy.checkConnection(execCtx), is(valid()));
  verify(tfsCommand, times(1)).checkConnection();
}

代码示例来源:origin: square/picasso

@Test
public void intoImageViewSetsPlaceholderDrawable() {
 PlatformLruCache cache = new PlatformLruCache(0);
 Picasso picasso =
   spy(new Picasso(RuntimeEnvironment.application, mock(Dispatcher.class), UNUSED_CALL_FACTORY,
     null, cache, null, NO_TRANSFORMERS, NO_HANDLERS, mock(Stats.class), ARGB_8888, false,
     false));
 ImageView target = mockImageViewTarget();
 Drawable placeHolderDrawable = mock(Drawable.class);
 new RequestCreator(picasso, URI_1, 0).placeholder(placeHolderDrawable).into(target);
 verify(target).setImageDrawable(placeHolderDrawable);
 verify(picasso).enqueueAndSubmit(actionCaptor.capture());
 assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void importSelectorsWithGroup() {
  DefaultListableBeanFactory beanFactory = spy(new DefaultListableBeanFactory());
  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(beanFactory);
  context.register(GroupedConfig.class);
  context.refresh();
  InOrder ordered = inOrder(beanFactory);
  ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any());
  ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
  ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
  ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
  assertThat(TestImportGroup.instancesCount.get(), equalTo(1));
  assertThat(TestImportGroup.imports.size(), equalTo(1));
  assertThat(TestImportGroup.imports.values().iterator().next().size(), equalTo(2));
}

代码示例来源:origin: bumptech/glide

@Test
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void testDoesNotThrowIfAskedToGetManagerForActivityPreJellYBeanMr1() {
 Util.setSdkVersionInt(Build.VERSION_CODES.JELLY_BEAN);
 Activity activity = Robolectric.buildActivity(Activity.class).create().start().resume().get();
 Activity spyActivity = Mockito.spy(activity);
 when(spyActivity.isDestroyed()).thenThrow(new NoSuchMethodError());
 assertNotNull(retriever.get(spyActivity));
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void testSingleWithBackpressureFlowable() {
  Flowable<Integer> flowable = Flowable.just(1, 2).singleElement().toFlowable();
  Subscriber<Integer> subscriber = spy(new DefaultSubscriber<Integer>() {
    @Override
    public void onStart() {
      request(1);
    }
    @Override
    public void onComplete() {
    }
    @Override
    public void onError(Throwable e) {
    }
    @Override
    public void onNext(Integer integer) {
      request(1);
    }
  });
  flowable.subscribe(subscriber);
  InOrder inOrder = inOrder(subscriber);
  inOrder.verify(subscriber, times(1)).onError(isA(IllegalArgumentException.class));
  inOrder.verifyNoMoreInteractions();
}

代码示例来源: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: neo4j/neo4j

private static ResourceIterator<File> scanStoreFilesAre( LabelScanStore labelScanStore, String[] fileNames )
{
  ArrayList<File> files = new ArrayList<>();
  mockFiles( fileNames, files, false );
  ResourceIterator<File> snapshot = spy( asResourceIterator( files.iterator() ) );
  when( labelScanStore.snapshotStoreFiles() ).thenReturn( snapshot );
  return snapshot;
}

代码示例来源:origin: oblac/jodd

@Test
void testAddClassChecksWithCache() throws Exception {
  ValidationContext context = spy(new ValidationContext());
  try {
    context.addClassChecks(ClassForCheck1.class);
    context.addClassChecks(ClassForCheck1.class);
  } finally {
    context.clearCache();
  }
  //collectProperty must be invoked only for first call of addClassChecks. Two calls for two annotations
  verify(context, times(2)).collectPropertyAnnotationChecks(any(List.class), any(PropertyDescriptor.class));
}

代码示例来源:origin: gocd/gocd

@Before
public void setUp() throws Exception {
  pluginDirectory = temporaryFolder.newFolder("pluginDir");
  bundleDirectory = temporaryFolder.newFolder("bundleDir");
  goPluginDescriptorBuilder = spy(new GoPluginDescriptorBuilder());
  doReturn(bundleDirectory).when(goPluginDescriptorBuilder).bundlePath();
}

相关文章