我有一个@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() {{ ... }}
能否请您帮助我确定此异常的原因?
答案 0 :(得分:0)
您似乎需要为方法调用提供模拟
mPersonService.update(personIfExists.get());
这是控制器方法的return语句。
我还相信该方法在服务中还具有另一个对getFileDetails的方法调用。
因此,如果为这两个方法调用提供模拟,则您的测试应该可以工作。