Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring WebTestClient response object is different from expected

I have a controller unit test using WebTestClient and it’s failing on the isEqualTo() test. I can’t find what’s wrong as I’m using the same object to set what the service call will return and the parameter for isEqualTo()

When I run the test I’m getting something like

Expected :com.model.Response@ab41b46
Actual   :com.model.Response@c1dcdb9

Model: This is just a portion of it but the other objects are just Strings

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Response implements Serializable {
    private static final long serialVersionUID = 1L; //random long
    private String id;
    private Long amount;
    private LocalDateTime dateTime;
    private String status;

    //setters-getters
}

Controller:

@PostMapping
public Mono<Response> getResponse() {
     return myService.getResponse();
}

Test:

@ExtendWith(MockitoExtension.class)
@WebFluxTest(controllers = MyController.class)
public class MyControllerTest
{
    @Autowired
    private transient WebTestClient webTestClient;

    @MockBean
    private transient MyService myService;

    @Test
    void shouldReturnResponse() {
        var response = new Response();
        response.id("id");
        response.setAmount(10L);
        when(myService.getResponse()).thenReturn(Mono.just(response));
        webTestClient.post()
                .uri("/")
                .exchange()
                .expectStatus().isOk()
                .expectBody(Response.class)
                .isEqualTo(response);
    }
}

As you can see I stubbed myService to return a Mono of response and just expected the same on isEqualTo()

I have some similar tests to this and they’re working fine. I’m currently checking if this is an issue with the Response object

>Solution :

isEqualTo uses the equals method to verify if objects are equal.

Judging from what you have posted here you haven’t implemented the equals method. No equals method means it will use the default which is basically checking if it is the same object instance. Which obviously isn’t true.

Hence either implement a proper equals method or use a different way of asserting your result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading