Search code examples
javatestinggroovyspock

Testing My model mapper with spock and all test passes


Hello I have a problem with spock groovy testing. I need to write a Unit test for my model mapper, but always my test passes ok even I want to write wrong: This is My model mapper:

public class ModelMapper {
    public ConferenceRoomDto fromConferenceRoomToConferenceRoomDto(ConferenceRoom conferenceRoom) {
        return conferenceRoom == null ? null : ConferenceRoomDto.builder()
                .roomName(conferenceRoom.getRoomName())
                .description(conferenceRoom.getDescription())
                .projector(conferenceRoom.getProjector())
                .phoneNumber(conferenceRoom.getPhoneNumber())
                .numberOfSeats(conferenceRoom.getNumberOfSeats())
                .build();

And this is My test:

given:
    ConferenceRoom conferenceRoom1 = ConferenceRoom.builder()
            .roomName("r")
            .projector(true)
            .description("d")
            .phoneNumber("23")
            .build()
    when:
    modelMapper.fromConferenceRoomToConferenceRoomDto(conferenceRoom1)
    then:
    ConferenceRoomDto conferenceRoomDto1 = ConferenceRoomDto.builder()
            .build()
}

This tets should fail because I give values to my conference room and I expect dto without values but all test pass ok.


Solution

  • OK - so there are two problems with you test here.

    1. = means assignment. To check for equality you need to use == on the last line of your test. This is not a Spock-specific thing - it's a general rule that applies in every programming language I've come across:

      • a = b means assign the value b to the variable a.
      • a == b means 'true' if a and b are in some way 'equal', 'false' otherwise.

      Spock expects code in a then block to end in an expression that can be evaluated as true (indicating the test passed) or false.

    2. Your last line, even if it used the right == operator, is not actually comparing your expected value with the value returned by the previous line. I believe what you're looking for is:

      when:
      def result = modelMapper.fromConferenceRoomToConferenceRoomDto(conferenceRoom1)
      then:
      result == ConferenceRoomDto.builder().build()
      

      In Spock, I believe a more idiomatic way of expressing this would simply be:

      expect:
      modelMapper.fromConferenceRoomToConferenceRoomDto(conferenceRoom1)
          == ConferenceRoomDto.builder().build()
      

    To reiterate, neither of these 2 problems are related to your use of Spock. You would have the same problem in any test framework or programming language, or even outside of testing.