Search code examples
javaspringjunit

java.lang.AssertionError: Status expected:<200> but was:<201>


Hi I'm trying to implement junit in my controller. But what I get is 201 instead of 200.

Below is my controller

@RestController
@RequestMapping(value = "/treat")
public class TreatController {

  private final TreatService treatService;

@Autowired
  public TreatController(TreatService treatService){
    this.treatService = treatService;
  }

@PostMapping
  public ResponseEntity<CommonResponse> addNew(
      @RequestBody Treat treat) throws RecordNotFoundException{
    CommonResponse response = new CommonResponse();
    response.setStatus(CommonConstants.OK);
    response.setData(treatService.save(treat));
    return new ResponseEntity<>(response, HttpStatus.CREATED);
  }
}

next is my Junit testing:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(TreatController.class)
public class TreatControllerTest {

  private RecordNotFoundException recordException = new RecordNotFoundException("");

  private final String title = "{\"title\" : \"title\"}";

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private TreatService treatService;

@Test
  public void addNew() throws Exception{
    Treatment treatment = new Treatment();

    given(treatmentService.save(
        Mockito.any(Treat.class))).willReturn(treat);
    mockMvc.perform(post("/treats")
    .content(title)
    .accept(MediaType.APPLICATION_JSON_VALUE)
    .contentType(MediaType.APPLICATION_JSON_VALUE))

    .andDo(print())
    .andExpect(status().isOk());

    Mockito.verify(treatService).save(Mockito.any(Treat.class));
  }
}

is there anything that I missed? By the way, I dont use Json. I just inserted it because it works.


Solution

  • That's what you return.

    return new ResponseEntity<>(response, HttpStatus.CREATED);
    

    HttpStatus.CREATED returns 201 and indicates that a resource has been created by the request

    How ever in your testcase you are expecting OK(200) .andExpect(status().isOk());

    According to HTTP1.1/ specs Post request should always result in the creation of a resource. So it makes sense to return 201 from there. All your need to do is change your testcase assertion expected value to HTTPStatus.CREATED.