#java #spring-boot #mockito
Вопрос:
Я пытаюсь проверить пользователей моего маршрута/логин
Контроллер
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public UserGetDTO loginUser(@RequestBody UserPostDTO userPostDTO) {
// convert API user to internal representation
User userInput = DTOMapper.INSTANCE.convertUserPostDTOtoEntity(userPostDTO);
System.out.println("Login user-------" userInput); // not null
// check if user exists
User loginUser = userService.checkForLogin(userInput);
System.out.println("Login user-------" loginUser); // it is null
// convert internal representation of user back to API
System.out.println(DTOMapper.INSTANCE.convertEntityToUserGetDTO(loginUser));
return DTOMapper.INSTANCE.convertEntityToUserGetDTO(loginUser);
}
@Test
public void check_login_test() throws Exception {
User user = new User();
user.setId(1L);
user.setName("Test User");
user.setUsername("testUsername");
user.setToken("1");
user.setPassword("password");
user.setStatus(UserStatus.ONLINE);
//given(userService.createUser(Mockito.any())).willReturn(user);
// given(userService.createUser(Mockito.any())).willReturn(user);
userService.createUser(user);
//System.out.println("9999" userService.createUser(user));
UserPostDTO userPostDTO = new UserPostDTO();
userPostDTO.setName("Test User");
userPostDTO.setUsername("testUsername");
userPostDTO.setPassword("password");
MockHttpServletRequestBuilder postRequest = post("/users/login")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(userPostDTO));
// then
MvcResult result = mockMvc.perform(postRequest)
.andExpect(status().is(200)).andReturn();
System.out.println(result.getResponse().getContentAsString()); // its null
}
Я создаю пользователя перед входом в систему и пытаюсь войти с тем же пользователем, но он всегда равен нулю.
Пользователи/логин работают отлично, но в тесте он не работает, также я использую базу данных h2 в памяти. Я предполагаю, что проблема связана с h2 db, пожалуйста, предложите любое решение.
Это мой полный файл UserContoller.test
/**
* UserControllerTest
* This is a WebMvcTest which allows to test the UserController i.e. GET/POST request without actually sending them over the network.
* This tests if the UserController works.
*/
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
//@Autowired
@MockBean
private UserService userService;
@Autowired
private UserService userService1;
@Test
public void givenUsers_whenGetUsers_thenReturnJsonArray() throws Exception {
// given
User user = new User();
user.setName("Firstname Lastname");
user.setUsername("firstname@lastname");
user.setStatus(UserStatus.OFFLINE);
List<User> allUsers = Collections.singletonList(user);
// this mocks the UserService -> we define above what the userService should return when getUsers() is called
given(userService.getUsers()).willReturn(allUsers);
// when
MockHttpServletRequestBuilder getRequest = get("/users").contentType(MediaType.APPLICATION_JSON);
// then
mockMvc.perform(getRequest).andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].name", is(user.getName())))
.andExpect(jsonPath("$[0].username", is(user.getUsername())))
.andExpect(jsonPath("$[0].status", is(user.getStatus().toString())));
}
@Test
public void createUser_validInput_userCreated() throws Exception {
// given
User user = new User();
user.setId(1L);
user.setName("Test User");
user.setUsername("testUsername");
user.setToken("1");
user.setStatus(UserStatus.ONLINE);
UserPostDTO userPostDTO = new UserPostDTO();
userPostDTO.setName("Test User");
userPostDTO.setUsername("testUsername");
given(userService.createUser(Mockito.any())).willReturn(user);
// when/then -> do the request validate the result
MockHttpServletRequestBuilder postRequest = post("/users/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(userPostDTO));
// then
MvcResult result= mockMvc.perform(postRequest)
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id", is(user.getId().intValue())))
.andExpect(jsonPath("$.name", is(user.getName())))
.andExpect(jsonPath("$.username", is(user.getUsername())))
.andExpect(jsonPath("$.status", is(user.getStatus().toString()))).andReturn();
System.out.println(result.getResponse().getContentAsString());
}
/// Test for checking login
@Test
public void check_login_test() throws Exception
{
/*
User user = new User();
user.setId(1L);
user.setName("Test User");
user.setUsername("testUsername");
user.setToken("1");
user.setPassword("password");
user.setStatus(UserStatus.ONLINE);
*/
//given(userService.createUser(Mockito.any())).willReturn(user);
//given(userService.createUser(Mockito.any())).willReturn(user);
//System.out.println("9999" userService.createUser(user));
UserPostDTO userPostDTO = new UserPostDTO();
userPostDTO.setName("Test User");
userPostDTO.setUsername("testUsername");
userPostDTO.setPassword("password");
MockHttpServletRequestBuilder postRequest = post("/users/login")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(userPostDTO));
// then
MvcResult result= mockMvc.perform(postRequest)
.andExpect(status().is(200)).andReturn();
System.out.println(result.getResponse().getContentAsString());
}
@BeforeEach
public void createUser() {
System.out.println("Before ran");
User user = new User();
user.setId(1L);
user.setName("Test User");
user.setUsername("testUsername");
user.setToken("1");
user.setPassword("password");
user.setStatus(UserStatus.ONLINE);
User user1= userService1.createUser(user);
// System.out.println("Before ran -----" user1.toString());
}
/**
* Helper Method to convert userPostDTO into a JSON string such that the input can be processed
* Input will look like this: {"name": "Test User", "username": "testUsername"}
* @param object
* @return string
*/
private String asJsonString(final Object object) {
try {
return new ObjectMapper().writeValueAsString(object);
}
catch (JsonProcessingException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, String.format("The request body could not be created.%s", e.toString()));
}
}
}
Я пробовал создавать объект внутри метода с помощью @раньше, но это тоже не работает
Комментарии:
1. предоставьте тестовому классу конфигурацию
2. @KrzysztofK обновил вопрос