簡體   English   中英

測試返回true,而返回false,反之亦然

[英]The test returns true, while it should return false and vice versa

我的線程的繼續如何使用Mockito正確測試Spring Boot 還有另一個問題。

好吧,這種方法

@GetMapping("/checkUsernameAtRegistering")
public HttpEntity<Boolean> checkUsernameAtRegistering(@RequestParam String username) {
        return ResponseEntity.ok().body(!userService.existsByUsername(username));
}

收到用戶名並檢入數據庫后,如果用戶名存在,則應返回false。 但是,測試

@Test
public void textExistsUsername() throws Exception {
    mockMvc
            .perform(get("/checkUserData/checkUsername")
            .param("username", "jonki97"))
            .andExpect(status().isOk())
            .andExpect(content().string("false"));
}

返回true。 我有一個使用該用戶名的用戶,該方法應返回false。 但是,事實並非如此。

java.lang.AssertionError: Response content 
Expected :false
Actual   :true

我想我很懂語法

.andExpect(content().string("false"));

我期待一串假值。 如何告訴服務返回什么?

您可以使用Mockito的when來模擬服務的返回。

@Test
public void textExistsUsername() throws Exception {
    when(userService.existsByUsername("jonki97")).thenReturn(true);
    mockMvc
            .perform(get("/checkUserData/checkUsername")
            .param("username", "jonki97"))
            .andExpect(status().isOk())
            .andExpect(content().string("false"));
}

暫無
暫無

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

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