简体   繁体   中英

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

Continuation of my thread How to properly test a Spring Boot using Mockito . There was another problem.

Well, this method

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

After receiving the username and checking in the database should return false if the username exists. However, the test

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

Returns true. I have a user with that username, and the method should return false. However, it is not.

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

I think I understand syntax well

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

I'm expecting a string of false value. How to tell the service what to return?

You can mock service's return with Mockito's 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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM