1
\$\begingroup\$

Is this correctly written test? Tested class is responsible for converting from dto to entity class and i wanted to test it. Are these tests useful and well designed? I have a problem understanding how should look such classes.


Tested class:

@Service 
public class ConverterRegisterUserDto extends Converter<RegisterUserDto,User> {

  private final PasswordEncoder passwordEncoder;

  @Autowired
  public ConverterRegisterUserDto(PasswordEncoder passwordEncoder, ModelMapper modelMapper) {
    super(modelMapper);
    this.passwordEncoder = passwordEncoder;
  }

  @Override
  public User convert(RegisterUserDto dto) {
    User user = modelMapper.map(dto, User.class);
    user.setPassword(encodePassword(dto.getPassword()));
    return user;
  }

  private String encodePassword(String password){
    return passwordEncoder.encode(password);
  }
}

Test:

class ConverterRegisterUserDtoTest {

    private PasswordEncoder passwordEncoder;
    private ConverterRegisterUserDto converterRegisterUserDto;
    private RegisterUserDto registerUserDto;

    @BeforeEach
    void init(){
        ModelMapper modelMapper = new ModelMapper();
        passwordEncoder = new BCryptPasswordEncoder();
        converterRegisterUserDto = new ConverterRegisterUserDto(passwordEncoder, modelMapper);
        registerUserDto = getSampleRegisterUserDto();
    }

    private RegisterUserDto getSampleRegisterUserDto(){
        RegisterUserDto registerUserDto = new RegisterUserDto();
        registerUserDto.setUsername("t_username");
        registerUserDto.setPassword("t_password");
        registerUserDto.setEmail("t_email");
        registerUserDto.setClientVerifyAccountUrl("t_url");
        return registerUserDto;
    }

    @Test
    void encodePassword_correctly(){
        //WHEN
        User user = converterRegisterUserDto.convert(registerUserDto);

        //THEN
        assertNotEquals(registerUserDto.getPassword(), user.getPassword());
        assertTrue(passwordEncoder.matches(registerUserDto.getPassword(), user.getPassword()));
    }

    @Test
    void convert_fromRegisterUserDto_toUserDtoClass(){
        //WHEN
        User user = converterRegisterUserDto.convert(registerUserDto);

        //THEN
        assertEquals(User.class, user.getClass());
    }

    @Test
    void convert_fromRegisterUserDto_isMappingCorrectly(){
        //WHEN
        User user = converterRegisterUserDto.convert(registerUserDto);

        //THEN
        assertEquals(registerUserDto.getUsername(), user.getUsername());
        assertEquals(registerUserDto.getEmail(), user.getEmail());
    }
}

I am trying to understand how to write good tests. Is that a good way? Or am I totally missing an idea of testing?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.