【发布时间】:2018-08-14 19:21:00
【问题描述】:
我定义了一个 @RestController 用于将 Person 类更新为:
@RestController
@RequestMapping("/api/person")
class PersonRestController {
@Autowired
private IPersonService mPersonService;
@PostMapping("/update")
public Person updatePerson(@RequestBody Person person) {
Optional<Person> personIfExists = mPersonService.findOneIfExists(person.id);
if (!personIfExists.isPresent()) {
throw new IllegalArgumentException();
}
return mPersonService.update(personIfExists.get());
}
}
为简洁起见,我们假设存在IPersonService 及其正确实现。该实现标有@Service,位于spring boot 组件扫描路径上。我正在使用JMockit、TestNG 和Spring MVC Test 框架来测试这个控制器。我还使用GSON 将Person 对象转换为JSON。这是我的测试方法:
@Test
public void testUpdateFileDetails() throws Exception {
Person person = new Person();
person.id = "P01";
person.name = "SOME_PERSON_NAME";
person.age = 99;
new Expectations() {{
mockedPersonService.findOneIfExists("P01");
result = new IllegalArgumentException();
}};
String personJson = new Gson().toJson(person);
mvc.perform(post("/api/person/update").content(personJson))
.andExpect(status().is4xxClientError());
}
当我运行这个测试用例时,我不断收到以下异常:
Missing 1 invocation to:
com.mytestapplication.services.api.IPersonService#getFileDetails("P01")
on mock instance: com.mytestapplication.services.api.$Impl_IPersonServcie@8c11eee
Caused by: Missing invocations
at com.mytestapplication.rest.api.PersonRestControllerTest$2.<init>(PersonRestControllerTest.java:<line_number>)
at com.mytestapplication.rest.api.PersonRestControllerTest.testUpdatePerson(PersonRestControllerTest.java:<line_number>)
这里指的是包含语句的行:new Expectations() {{ ... }}
您能帮我找出这个异常的原因吗?
【问题讨论】:
标签: java spring-boot testng jmockit spring-mvc-test