gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:53:03 26 4
gpt4 key购买 nike

嗨,我正在尝试在我的 Controller 中实现 junit。但我得到的是 201 而不是 200。

下面是我的 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);
}
}

接下来是我的 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。我只是插入它,因为它有效。

最佳答案

这就是你返回的内容。

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

HttpStatus.CREATED 返回 201 并指示请求已创建资源

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

根据HTTP1.1/ specs Post 请求应该始终导致资源的创建。所以从那里返回 201 是有意义的。您所需要做的就是将测试用例断言预期值更改为 HTTPStatus.CREATED。

关于java.lang.AssertionError : Status expected:<200> but was:<201>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com