测试方法有问题。我有restcotroller,我想测试删除方法(选项 - 不应该从数据库中删除对象)。 这是我在服务类中的方法:
public Optional<PersonDto> deletePerson(Long id) {
Assert.notNull(id, "id can't be null");
Optional<Person> personOptional = personRepository.findById(id);
personRepository.deleteById(id);
return personOptional.map(p -> modelMapper.map(p, PersonDto.class));
}
这是我有问题的测试方法:
@Test
public void shouldNotDeletePersonByGivenId() throws Exception {
Mockito.doThrow(new NoEntityFoundException()).when(personService).deletePerson(1L);
mockMvc.perform(delete("/people/{id}", 1L))
.andExpect(status().isBadRequest());
}
此测试中的错误是:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.softwaremind.crew.people.service.NoEntityFoundException: There is no Entity in database with this id.
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:899)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:667)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:68)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:165)
at com.softwaremind.crew.people.controller.PersonRestControllerTest.shouldNotDeletePersonByGivenId(PersonRestControllerTest.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: com.softwaremind.crew.people.service.NoEntityFoundException: There is no Entity in database with this id.
at com.softwaremind.crew.people.controller.PersonRestController.deletePerson(PersonRestController.java:83)
异常类:
public class NoEntityFoundException extends RuntimeException {
public NoEntityFoundException() {
super("There is no Entity in database with this id.");
}
}
答案 0 :(得分:0)
尝试将@Test
注释更改为@Test(expected=NoEntityFoundException.class)