简体   繁体   English

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

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

I have to impelement a test for MyService that conntain two methods method1 & method2:我必须对包含两个方法方法 1 和方法 2 的 MyService 进行测试:

and the method1 call method2 (method1 --> method2 )和 method1 调用 method2 (method1 --> method2 )

so i've somthing like this in my test class所以我在我的测试 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


... 

so i want to test my method1 but with the mock of method ( even my service class is autowired not mocked)所以我想测试我的方法1,但使用方法的模拟(甚至我的服务 class 是自动装配的而不是模拟的)

Thanks谢谢

Mockito supports what I will call "partial mocking"; Mockito 支持我所说的“部分模拟”; it is called Spy.它被称为间谍。

Instead of creating a mock bean for your service, create a Spy.与其为您的服务创建一个模拟 bean,不如创建一个 Spy。 Also, as mentioned in other answers, don't user @Autowire for the service.此外,如其他答案中所述,请勿使用@Autowire服务。

Here is some example code:这是一些示例代码:

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.
    }
}

Create two Services for those two Methods.为这两个方法创建两个服务。 Then you can mock one service to test the other.然后,您可以模拟一项服务来测试另一项服务。

Lets assume that your Service look like that:让我们假设您的Service看起来像这样:

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

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

So if you willing to Mock the method2 function you we'll need to use a Mocked Bean for that using Spring & Mockito因此,如果您愿意模拟方法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