我必须对包含两个方法 method1 和 method2 的 MyService 进行测试:
并且 method1 调用 method2 (method1 --> method2 )
所以我的测试类中有这样的东西
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootApplicationTest.class)
@ContextConfiguration(classes = { conf.class })
public class CommonCAMServiceTest {
@Autowired
private MyService myService;
test_method_1(){...}// this is what i want to implement and i have to mock the method2 call
test_method_2(){...}//this work fine
...
所以我想测试我的方法1,但是使用方法的模拟(甚至我的服务类是 Autowiring 的而不是模拟的)
谢谢
最佳答案
Mockito 支持我所说的“部分模拟”; 它被称为 spy 。
无需为您的服务创建模拟 bean,
创建一个 spy 。
还,
正如其他答案中提到的,
不要使用 @Autowire
来使用该服务。
这里是一些示例代码:
public class CommonCAMServiceTest
{
@Spy
private MyService myService;
@Before
public void before()
{
MockitoAnnotations.initMocks(this);
// Mock method2 for every test.
doReturn(something).when(myService).method2();
}
@Test
public void someTestName()
{
// Mock method2 in this test.
doReturn(somethingElse).when(myService).method2();
... call method1 to do stuff.
}
}
关于java - 使用mockito和spring mock的authowired bean的Mock方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862424/