簡體   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