java MockMvc返回404
我编写了控制器,它为每个映射使用不同的值。现在我对它进行折射,以便对所有映射使用相同的值,但是我不知道如何使测试工作,因为它对每个映射返回404
这是我的控制器:
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/v1")
public class TaskController {
@Autowired
DbService dbService;
@Autowired
TaskMapper taskMapper;
@GetMapping(value = "/tasks")
public List<TaskDto> getTasks() {
return taskMapper.mapToTaskDtoList(dbService.getAllTask());
}
@GetMapping(value = "/tasks/{id}")
public TaskDto getTask(@PathVariable Long id) throws TaskNotFoundException {
return taskMapper.mapToTaskDto(dbService.getTask(id).orElseThrow(TaskNotFoundException::new));
}
@DeleteMapping(value = "/tasks/{id}")
public void deleteTask(@PathVariable Long id) {
dbService.deleteTask(id);
}
@PutMapping(value = "/tasks")
public TaskDto updateTask(@RequestBody TaskDto taskDto) {
return taskMapper.mapToTaskDto(dbService.saveTask(taskMapper.mapToTask(taskDto)));
}
@PostMapping(value = "/tasks", consumes = APPLICATION_JSON_VALUE)
public void createTask(@RequestBody TaskDto taskDto) {
dbService.saveTask(taskMapper.mapToTask(taskDto));
}
}
还有我的测试:
@RunWith(SpringRunner.class)
@WebMvcTest(TaskController.class)
public class TaskControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private DbService dbService;
@MockBean
private TaskMapper taskMapper;
@Test
public void shouldFetchAllTasks() throws Exception {
//Given
List<TaskDto> tasks = new ArrayList<>();
tasks.add(new TaskDto(1L, "test", "testing"));
tasks.add(new TaskDto(2L, "test2", "still_testing"));
when(taskMapper.mapToTaskDtoList(dbService.getAllTask())).thenReturn(tasks);
//When & Then
mockMvc.perform(get("/v1/task/tasks").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].title", is("test")))
.andExpect(jsonPath("$[0].content", is("testing")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].title", is("test2")))
.andExpect(jsonPath("$[1].content", is("still_testing")));
}
@Test
public void shouldFetchGivenTask() throws Exception {
//Given
List<TaskDto> tasks = new ArrayList<>();
tasks.add(new TaskDto(1L, "test", "testing"));
tasks.add(new TaskDto(2L, "test2", "still_testing"));
when(dbService.getTask(anyLong())).thenReturn(Optional.of(new Task(2L, "test2", "still_testing")));
when(taskMapper.mapToTaskDto(anyObject())).thenReturn(tasks.get(1));
//When & Then
mockMvc.perform(get("/v1/task/tasks/{id}", "2")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(2)))
.andExpect(jsonPath("$.title", is("test2")))
.andExpect(jsonPath("$.content", is("still_testing")));
}
@Test
public void shouldUpdateTask() throws Exception {
//Given
TaskDto taskDto = new TaskDto(1L, "test", "testing");
TaskDto updatedTaskDto = new TaskDto(1L, "updated task", "even more testing");
when(taskMapper.mapToTaskDto(dbService.saveTask(taskMapper.mapToTask(taskDto)))).thenReturn(updatedTaskDto);
Gson gson = new Gson();
String jsonContent = gson.toJson(taskDto);
//When & Then
mockMvc.perform(put("/v1/task/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonContent))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(1)))
.andExpect(jsonPath("$.title", is("updated task")))
.andExpect(jsonPath("$.content", is("even more testing")));
}
@Test
public void shouldDeleteTask() throws Exception {
//Given
//When & Then
mockMvc.perform(delete("/v1/task/tasks/{id}","1"))
.andExpect(status().isOk());
}
@Test
public void shouldCreateTask() throws Exception {
//Given
//When & Then
mockMvc.perform(post("/v1/task/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"another test\"," +
"\"content\":\"keep on testing\"}"))
.andExpect(status().isOk());
}
}
404和以下文件中的所有测试结果:
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59) at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:98) at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619) at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195) at com.crud.tasks.controller.TaskControllerTest.shouldFetchGivenTask(TaskControllerTest.java:74) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 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)
# 1 楼答案
url-
/v1/task/tasks
不存在于控制器中的任何请求映射中。您的类级控制器具有/v1
请求映射,而您的方法级请求映射具有/tasks
而非/task
,因此您将得到404未找到错误