我为下面的put方法编写了弹簧支架控制器的单元测试用例
@PutMapping("/offers/{jobTitle}")
public Offer updateOffer(@PathVariable String jobTitle,@Valid @RequestBody Offer offer) {
return offerService.updateNoOfPost(jobTitle, offer);
}
下面是我的服务班
@Override
public Offer updateNoOfPost(String jobTitle, Offer offer) {
if(!offerRepository.existsById(jobTitle))
throw new ResourceNotFoundException("JobTitle "+jobTitle+" not found !!");
offer.setNoOfPost(offer.getNoOfPost());
return offerRepository.save(offer);
}
我已经使用testNg和Mockito编写了此方法的单元测试用例
public class OfferControllerTest {
private MockMvc mvc;
private JacksonTester<Offer> jsonOffer;
@Mock
private OfferService service;
@InjectMocks
OfferController offerController;
private Offer offer;
@BeforeMethod
public void setup() {
offer = new Offer("LSE", new Date(),1);
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(offerController)
.build();
JacksonTester.initFields(this, new ObjectMapper());
}
@Test
public void updateOffer() throws Exception {
Mockito.when(service.updateNoOfPost("LSE", offer)).thenReturn(offer);
MockHttpServletResponse response = mvc.perform(
put("/offers/LSE").contentType(MediaType.APPLICATION_JSON).content(
jsonOffer.write(new Offer("SE", new Date(), 19)).getJson()
)).andReturn().getResponse();
assertThat(response.getContentAsString()).isEqualTo(new ObjectMapper().writeValueAsString(offer));
}
我得到的响应代码为200。但是body.pls出现空白,发现错误
FAILED: updateOffer
org.junit.ComparisonFailure: expected:<"[{"jobTitle":"LSE","createdAt":"2018-10-27","noOfPost":1}]"> but was:<"[]">
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
我想念什么?这是编写弹簧支架控制器的单元测试用例的标准方法吗?
答案 0 :(得分:0)
下面的模拟应该可以解决问题
Mockito.when(service.updateNoOfPost(Mockito.any(String.class), Mockito.any())).thenReturn(offer);
在此处了解更多信息:stack-46914252