从WebApplicationContext创建MockMvc和从Controller实例创建MockMvc之间的区别?

时间:2013-09-27 05:00:20

标签: spring-mvc spring-mvc-test

当我使用类似于此的WebApplicationContext使用spring MVC 3.2.3为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 Confuguration,而如果我使用Controller,那么它将不会。

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

EDIT 我的测试类

@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>

1 个答案:

答案 0 :(得分:0)

MockMvc期望Controller类初始化。看看我是如何做到的。

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


}