簡體   English   中英

Mockito 沒有返回預期的返回值

[英]Mockito not returning the expected return value

我正在研究 Java 項目並嘗試使用 Mockito。 這是我的測試代碼:

@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class TestMainController {
    @MockBean
    MainController mainController;

    @MockBean
    AnotherServiceImpl anotherService;

    @Autowired
    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(mainController).build();
    }

    @Test
    public void TestFirstFunctionFor201() throws Exception {
        String req = "<JSON_STRING>";
        when(anotherService.someFunction(Mockito.anyString())).thenReturn("Success");
        this.mockMvc.perform(put("/Main/one/").contentType(MediaType.APPLICATION_JSON)
                .content(req)).andExpect(status().isCreated());
    }
}

我當然要改名字。 這是 controller 代碼:

@PutMapping("/Main/one")
    public ResponseEntity<String> firstFunction(@RequestBody RequestObject requestObject){
        String result = anotherService.someFunction(requestOject.getName());
        if(Objects.equals(result, "Success")){
            return new ResponseEntity<>(result, HttpStatus.CREATED);
        }
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

所以我是 mocking firstFunction返回“成功”,但我沒有得到結果。 相反,正在執行實際的 function。 僅當req是適當的時,測試用例才通過。 換句話說,function 沒有被嘲笑。

請幫忙。

您不必模擬class或您要測試的方法 mocking 背后的想法是模擬您的依賴項。 在您的情況下,您要測試的 class 是MainController ,它取決於AnotherServiceImpl 沒關系,你已經模擬了你的依賴,所以你不必模擬MainController

此外,由於注釋@SpringBootTest將加載您的所有上下文,因此您在這里進行了集成測試 而且我想這不是您在使用MockMvc時想要的。 您必須使用帶有注釋的測試切片@WebMvcTest(MainController.class)

您的 class 應該看起來像這樣:

@WebMvcTest(TestMainController.class)
public class TestMainController {
    
    @MockBean
    AnotherServiceImpl anotherService;

    @Autowired
    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(mainController).build();
    }

    @Test
    public void TestFirstFunctionFor201() throws Exception {
        String req = "<JSON_STRING>";
        when(anotherService.someFunction(Mockito.anyString())).thenReturn("Success");
        this.mockMvc.perform(put("/Main/one/").contentType(MediaType.APPLICATION_JSON)
                .content(req)).andExpect(status().isCreated());
    }
}

暫無
暫無

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

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