java – MockMvc返回404状态

我正在尝试为控制器编写测试用例.我不想模仿我的服务,因为我想将这些测试用作完整的功能测试.

我正在尝试测试这个控制器:

@Controller
public class PlanController {

     @Autowired
     private PlanService planService;

     @RequestMapping(
        value = "/api/plans/{planId}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
     @ResponseBody
     @Nonnull
     @JsonView(Plan.SimpleView.class)
     public Plan getPlan(@RequestParam int orgId, @PathVariable int planId) {
         Plan plan = planService.getPlan(orgId, planId);
         return plan;
    }
}

这是我写的测试用例:

package com.videology.skunkworks.audiencediscovery.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.eclipse.jetty.webapp.WebAppContext;  
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class})
@WebAppConfiguration
@EnableWebMvc
public class PlanControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    }

    @Test
    public void testGetPlan() throws Exception {
        mockMvc.perform(get("/api/plans/1/?orgId=1").accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk());
    }
}

此测试用例失败,因为返回的status()是404而不是200.不确定为什么它返回404,因为errorMessage为null.

我遇到了很多类似的问题,但没有一个对我有帮助.

解决方法:

配置错误.
要解决这个问题,我必须在contextConfiguration中提供我的WebConfig文件.这是我添加的行:

@ContextConfiguration(classes = {WebConfig.class})
上一篇:java – 为什么Spring MockMvc结果不包含cookie?


下一篇:java.lang.AssertionError:预期状态:200实际:404