繁体   English   中英

使用 mockito 和 spring 模拟的 authowired bean 的模拟方法

[英]Mock Method of authowired bean using mockito and spring mock

我必须对包含两个方法方法 1 和方法 2 的 MyService 进行测试:

和 method1 调用 method2 (method1 --> method2 )

所以我在我的测试 class 中有这样的东西

@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,但使用方法的模拟(甚至我的服务 class 是自动装配的而不是模拟的)

谢谢

Mockito 支持我所说的“部分模拟”; 它被称为间谍。

与其为您的服务创建一个模拟 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.
    }
}

为这两个方法创建两个服务。 然后,您可以模拟一项服务来测试另一项服务。

让我们假设您的Service看起来像这样:

@Service
public class MyService {
    public void method1() {
        method2();
    }

    public void method2() {
        System.out.println("calling method 2");
    }
}

因此,如果您愿意模拟方法2 function,我们将需要使用模拟 Bean 来使用 Spring 和 Mockito

@MockBean // Use that instead of @Autowired, will create a Mocked Bean
public MyService service;

@Test
public void testing() {
    Mockito.doAnswer((Answer<Void>) invocation -> {
        System.out.println("mocked");

        return null;
    }).when(service).method2();


    Mockito.doCallRealMethod().when(service).method1();

    service.method1();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM