Java 如何模仿间谍的个别方法?

Java 如何模仿间谍的个别方法?,java,spring,mocking,mockito,spy,Java,Spring,Mocking,Mockito,Spy,我正在开发一个测试类,其中一个特定的测试需要实际实现我正在模拟的服务类的方法。所以我想,为什么不使用@SpyBean而不是@MockBean,在我需要的地方使用实际的实现(不需要做任何事情),在我需要的地方使用模拟实现(需要编写一个单行程序来设置模拟方法) 我发现,“@SpyBean to the rescue”一节解释了如何做到这一点 唯一的问题是它不起作用,使用了真正的实现,这些测试成功了,但是模拟的方法没有起作用。我使用的是Mockito 2.21.0和Spring框架5.1.0。现在我使

我正在开发一个测试类,其中一个特定的测试需要实际实现我正在模拟的服务类的方法。所以我想,为什么不使用
@SpyBean
而不是
@MockBean
,在我需要的地方使用实际的实现(不需要做任何事情),在我需要的地方使用模拟实现(需要编写一个单行程序来设置模拟方法)

我发现,“@SpyBean to the rescue”一节解释了如何做到这一点

唯一的问题是它不起作用,使用了真正的实现,这些测试成功了,但是模拟的方法没有起作用。我使用的是Mockito 2.21.0和Spring框架5.1.0。现在我使用单独的测试类来实现这一目的,但我想找出正确的方法

我所做的与本博客中的示例完全相同:

@SpringBootTest(classes = TestclassAA.class)
class TestclassAA {
@SpyBean
private XXService xxService;

private ClassUsingXXService testee;

@Test
void test1 {
   // ..
   // use mocked implementation of save() -> does not work, real method called
   doReturn(new XXRequestModel()).when(xxService).save(any(XXModel.class));
   var result = testee.doSomething();
   //.. 
}

@Test
void test2 {
  // ..
  // use actual implementation of save() -> works, real method called
  var result = testee.doSomething();
  //.. 
}
基本上,我收到的错误消息暗示,我所做的是不可能与间谍:

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();

E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();

Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

有人知道怎么做吗?

你的代码是什么,你到底想实现什么(在代码中),应该调用什么方法?我假设在同一个测试类中有两个测试,我想要一个SpyBean,在我这么说时调用一个模拟方法,否则不行。有关详细信息,请参阅更新的帖子这是您的完整测试类吗?我至少希望有一个
@RunWith
注释……为了简单起见,这当然是一个精简版。这个班有它所需要的一切。我已经运行了所有程序,只是在spybean上设置模拟方法失败了。但我会稍微修改一下发布的代码