java.lang.AssertionError: No ModelAndView found using webAppContextSetup

java.lang.AssertionError: No ModelAndView found using webAppContextSetup

我想测试这个控制器:

@Controller
@RequestMapping(value = "/bookmanagement")
public class BookManagementController {

    @RequestMapping(value = "")
    public String bookManagement(HttpSession session, HttpServletRequest request, Model model, Authentication auth) {

        // does stuff
        return "bookManagement";
    }

    @RequestMapping(value = "edit")
    public String edit(HttpSession session, HttpServletRequest request, Model model, Authentication auth,
            @RequestParam(value = "id", required = true) String id) {

        // does stuff

        return "editBook";
    }

    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public String fileUpload(@RequestParam("coverFile") MultipartFile file,
            @RequestParam(value = "type", required = true) String type,
            @RequestParam(value = "id", required = true) String id,
            @RequestParam(value = "pages", required = true) String pages, HttpServletResponse response, Model model)
            throws JSONException {

        // writes file

        return "editBook_File";

    }


}

请注意RequestMapping。所以这是我的 JUnit 测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("file:application/webapp")
@ContextConfiguration("file:application/webapp/WEB-INF/dispatcher-servlet.xml")
public class BookManagementControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private UsersRepository usersCollection;

    @Resource
    private FilterChainProxy springSecurityFilterChain;

    @Resource
    private WebApplicationContext webApplicationContext;

    private MockHttpSession session;

    @InjectMocks
    private BookManagementController bookManagementController;

    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .addFilter(springSecurityFilterChain)
                .build();

        this.session = getSessionWithAuthentication();

    }

    @Test
    public void editTestView() throws Exception {

        this.mockMvc.perform(get("/bookmanagement/edit?id=58385d39bd7f3513c83faa65").session(session))
                .andExpect(view().name("editBook")).andExpect(status().isOk()).andReturn();

    }

    @Test
    public void uploadCoverFile() throws Exception {

        MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json",
                "{\"json\": \"someValue\"}".getBytes());

        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/bookmanagement/fileUpload").file(jsonFile))
                .andExpect(view().name("editBook_File")).andExpect(status().isOk()).andReturn();

    }

    private MockHttpSession getSessionWithAuthentication() {
        Users testPodUser = usersCollection.findByEmail("test@pod.de");
        SecUserDetails principal = new SecUserDetails(testPodUser);
        SecurityContext secContext = SecurityContextHolder.getContext();
        secContext.setAuthentication(new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
                principal.getAuthorities()));

        MockHttpSession session = new MockHttpSession();
        session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, secContext);

        return session;
    }

}

dispatcher-servlet.xml在controller所在的包中包含组件扫描,当我手动测试controller时,一切正常。

所以第一个测试 (editTestView()) returns 绿色。但是第二个失败并出现此错误:

java.lang.AssertionError: No ModelAndView found
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:39)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:72)
    at org.springframework.test.web.servlet.result.ViewResultMatchers.match(ViewResultMatchers.java:68)
    at org.springframework.test.web.servlet.MockMvc.andExpect(MockMvc.java:171)
    at de.mypackage.prod.controller.BookManagementControllerTest.uploadCoverFile(BookManagementControllerTest.java:85)
    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.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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access[=12=]0(ParentRunner.java:58)
    at org.junit.runners.ParentRunner.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:193)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

我不明白为什么 get("/bookmanagement/edit?id=58385d39bd7f3513c83faa65") 调用可以正常工作,但另一方面 fileUpload("/bookmanagement/fileUpload") 却不行。

我在这里错过了什么?

它失败了,因为,

文件的预期名称是 coverFile

@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public String fileUpload(@RequestParam("coverFile") MultipartFile file,
            @RequestParam(value = "type", required = true) String type,
            @RequestParam(value = "id", required = true) String id,
            @RequestParam(value = "pages", required = true) String pages, HttpServletResponse response, Model model)
            throws JSONException {

但是您将名称传递为 json,

MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json",
                "{\"json\": \"someValue\"}".getBytes());

您需要将其修复为,

MockMultipartFile jsonFile = new MockMultipartFile("coverFile", "", "application/json",
                    "{\"json\": \"someValue\"}".getBytes());

同时检查处理程序方法的其他必需参数。