java.lang.AssertionError:期望的状态:< 200>但是:< 201>

时间:2018-06-01 06:46:25

标签: java spring junit sp

您好我试图在我的控制器中实现junit。但我得到的是201而不是200。

以下是我的控制器

@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);
  }
}

接下来是我的Junit测试:

@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));
  }
}

有什么我错过的吗? 顺便说一句,我不使用Json。我刚刚插入它,因为它有效。

1 个答案:

答案 0 :(得分:3)

那是你的回报。

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

HttpStatus.CREATED返回 201 ,表示请求已创建资源

在您的测试用例中,您期望OK(200).andExpect(status().isOk());

根据HTTP1.1/ specs发布请求应始终导致创建资源。因此从那里返回201是有道理的。您需要做的就是将您的testcase断言期望值更改为HTTPStatus.CREATED。