簡體   English   中英

如何使用JUnit / Mockito處理模擬方法的副作用

[英]How to deal with side effects of mocked method with JUnit/Mockito

這可能是一個愚蠢的問題,也可能是顯而易見的問題,但盡管如此,我仍在努力解決這個問題。 假設我們在被測方法中具有以下邏輯:

@Service
public class ServiceToTest() {

    @Autowired
    private SomeService someService;

    public String testMethod() {
        Map<String, String> parameters = new HashMap<String, String>();
        // eventParameters will be populated inside someService
        String result = someService.doLogic(parameters);
        // do something with the result here that doesn't really matter for this example
        String name = parameters.get("name").toLowerCase();
        return name;
    }
}

SomeService內部,參數圖填充了一些值,例如本示例中的“名稱”。 我想在單元測試中模擬此服務。

考慮以下單元測試代碼段:

@RunWith(SpringRunner.class)
public class ServiceToTestTest {

    @TestConfiguration
    static class ServiceToTestConfiguration {
        @Bean
        public ServiceToTest serviceToTest() {
            return new ServiceToTest();
    }

    @Autowired
    private ServiceToTest serviceToTest;

    @MockBean
    private SomeService someService;

    @Test
    public void testShouldReturnJimmy() {
        given(someService.doLogic(Mockito.anyMap())).willReturn("whatever");
        String name = serviceToTest.testMethod();
        assertThat(name).isEqualTo("jimmy");
    }
}

當我執行此測試時,在此行上得到一個NullPointerException: String name = parameters.get("name").toLowerCase(); ,這是有道理的,因為應該填充此地圖的方法是模擬的,而parameters.get("name")為null。 我們還假設我真的想從doLogic(parameters)返回一個String,因此它不能是參數map。

有什么方法可以指示模擬對象填充參數映射或模擬映射對象本身嗎?
(這里的代碼示例是為即時編寫的,因此,如果在編寫它們時沒有發現任何愚蠢的錯誤,請原諒我;-))

可以使用有爭議的thenAnswer方法來完成。

https://static.javadoc.io/org.mockito/mockito-core/2.13.0/org/mockito/stubbing/OngoingStubbing.html#thenAnswer-org.mockito.stubbing.Answer-

但是JB的評論是正確的。 這不是一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM