Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring boot unit testing using testng

How to write a POST method test case if the return type of a particular create method in the service layer is ResponseEntity<Object>?

This is my createOffer method:

public ResponseEntity<Object> createOffer(Offer offer) {
    Offer uoffer = offerRepository.save(offer);


    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
                    buildAndExpand(uoffer.getJobTitle()).toUri();

    return ResponseEntity.created(location).build();

}

and this is its corresponding test class method:

@Test
public void testCreateOffer() {
    Offer offer = new Offer("SE",new Date(),5);
    Mockito.when( offerRepository.save(offer)).thenReturn( offer);
    assertThat(offerServiceImpl.createOffer(offer)).isEqualTo(offer);
}

Here I am getting an error while running this test case which is no current servlet request attributes and exception is:

java.lang.IllegalStateException

Why is it coming

like image 296
Aditya Avatar asked Sep 03 '25 03:09

Aditya


1 Answers

This answers the above question.

Hope it helps when someone finds the same issue !!!

@Test
public void testCreateOffer() {
    Offer offer = new Offer("SE",new Date(),5);


    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));


    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
            buildAndExpand(offer.getJobTitle()).toUri();

    ResponseEntity<Object> response = ResponseEntity.created(location).build();
    Mockito.when( offerRepository.save(offer)).thenReturn(offer);
    assertThat( offerServiceImpl.createOffer(offer)).isEqualTo(response);
}
like image 180
Aditya Avatar answered Sep 06 '25 14:09

Aditya