6

当我使用 Spring MVC 3.2.3 使用 WebApplicationContext 为 restful-webservice 测试创建 MockMvc 时,如下所示:

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

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


// ...

}

然后当我运行我的测试时,它会失败并返回代码 404,我的日志说

Did not find handler method for [my/path]

但如果我改变这种方式

public class MyWebTests {

private MockMvc mockMvc;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}

// ...

}

然后我的测试将运行良好,没有任何错误。

我知道的唯一区别是,如果我使用 WebApplicationContext 创建 MockMvc,那么它将加载我的 Spring 配置,而如果我使用 Controller,则不会。

在我的情况下,什么可能导致该错误(未找到处理程序方法...)?

编辑我的测试课

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:restful-test-context.xml")
@WebAppConfiguration
public class TestSourceController {
@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;
private ObjectMapper mapper;

@Autowired
DeviceDAO deviceDAO;

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {
    Mockito.reset(deviceDAO);
    mockMvc = MockMvcBuilders.standaloneSetup(new SourceController()).build();
    mapper = new ObjectMapper();
}

@After
public void tearDown() throws Exception {
}

@Test
public void testGetAllDevice() throws UnsupportedEncodingException,
        Exception {
    Device device1 = new Device();
    device1.setId("switch1");
    device1.setIsRoot(true);
    device1.setName("switch1");
    device1.setStatus("ONLINE");
    device1.setType("SWITCH");

    Device device2 = new Device();
    device2.setId("switch2");
    device2.setIsRoot(true);
    device2.setName("switch2");
    device2.setStatus("OFFLINE");
    device2.setType("SWITCH");

    List<Device> devices = Arrays.asList(device1, device2);

    when(deviceDAO.getAllDevices()).thenReturn(devices);

    String expected = mapper.writeValueAsString(devices);

    String result = mockMvc
            .perform(get("/api/devices").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andReturn().getResponse()
            .getContentAsString();

    verify(deviceDAO).getAllDevices();

    assertEquals(expected, result);
}

}

我的控制器

@Controller
public class SourceController {

private static final Logger logger = LoggerFactory.getLogger("SourceController");

@RequestMapping(value = "/api/devices", method = RequestMethod.GET)
@ResponseBody
public List<Device> getAllDevice() {
    DeviceDAO deviceDAO = AppContext.getService(DeviceDAO.class,
            "deviceDAO");
    logger.info("The deviceDAO is" + deviceDAO.toString() + "!");
    return deviceDAO.getAllDevices();
}
}

我的 web.xml

<web-app version="2.5"  xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name>Spring Web MVC Application</display-name>

<servlet>
    <servlet-name>nhduc-training-app</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>nhduc-training-app</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/nhduc-training-app-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

我的 restful-test-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.tma.nhduc.controller" />


<bean id="daoUtils" class="com.tma.nhduc.dao.DAOUtils" />

<bean id="counterService" class="com.tma.nhduc.dao.SequenceService" />

<bean id="portDAO" class="com.tma.nhduc.dao.PortDAO" />

<bean id="alarmDAO" class="com.tma.nhduc.dao.AlarmDAO" />

<bean id="deviceDAO" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.tma.nhduc.dao.DeviceDAO"></constructor-arg>
</bean>
<bean id="appContext" class="com.tma.nhduc.ctx.AppContext" />

<mongo:mongo host="localhost" port="27017" />
<mongo:db-factory dbname="nms" mongo-ref="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>

4

1 回答 1

0

MockMvc 期望控制器类初始化。看看我是怎么做到的。

@InjectMocks
private SampleController controller = new SampleController();
@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
            .dispatchOptions(true).build();


}
于 2015-07-16T06:57:04.790 回答