簡體   English   中英

java.lang.AssertionError:預期狀態:<200>但原為:<201>

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

嗨,我正在嘗試在控制器中實現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));
  }
}

我有什么想念的嗎? 順便說一句,我不使用傑森。 我剛剛插入它是因為它有效。

那就是你的回報。

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

HttpStatus.CREATED返回201,並指示該請求已創建資源

在測試用例中,您期望的是OK(200) .andExpect(status().isOk());

根據HTTP1.1 / specs,發布請求應始終導致資源的創建。 因此從那里返回201很有意義。 您所需要做的就是將您的測試用例斷言期望值更改為HTTPStatus.CREATED。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM