Home > Software design >  Testing controller returns nothing instead of object
Testing controller returns nothing instead of object

Time:10-03

So Iam testing my UserController - create user and get user methods. When I run my tests, I get this output:

org.opentest4j.AssertionFailedError:
Expected :UserDTO(id=1, name=Steve, [email protected], group=null)
Actual   :

This is my test class:

@WebMvcTest(UserController.class)
class UserControllerTest {

  @MockBean private UserInterface userInterface;

  @Autowired private MockMvc mockMvc;

  @Test
  void create() throws Exception {
    UserCreationDTO user = new UserCreationDTO(1L, "Steve", "[email protected]", "password");

    Mockito.when(userInterface.create(user)).thenReturn(user);

    RequestBuilder request =
        MockMvcRequestBuilders.post("/api/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(String.valueOf(user));

    MvcResult result = mockMvc.perform(request).andReturn();
    assertEquals(user, result.getResponse().getContentAsString());
  }

  @Test
  void getUser() throws Exception {
    UserDTO userDTO = new UserDTO(1L, "Steve", "[email protected]", null);

    Mockito.when(userInterface.getUser(1L)).thenReturn(userDTO);

    RequestBuilder request = MockMvcRequestBuilders.get("/api/users/1");

    MvcResult result = mockMvc.perform(request).andReturn();
    assertEquals(userDTO, result.getResponse().getContentAsString());
  }
}

Can someone tell me what am I doing wrong and why Iam not getting any object when runing this tests? Im new o testing so Im sorry if this is some newbie question.

CodePudding user response:

Your tests try to compare your custom object - UserDTO with a String. This can't work, objects of different classes can never be equal. You have to compare objects from the same class. You need to either:

  1. Transform UserDTO to a string, whatever format you are using, and compare strings. This is error prone and not a good idea, or:
  2. Parse response to UserDTO and compare 2 UserDTOs. If you have not overridden equals() you can compare the fields using the getters.
  • Related