我已經升級了我的Spring依賴到Spring 3.1.1.RELEASE,我試圖用spring-test-mvc來單元測試一個簡單的控制器。我一直在遵循Spring REST Controller Test with spring-test-mvc framework中使用的技術,因爲它似乎已經爲那個人工作,但迄今爲止我一直沒有成功。我覺得有一些關鍵配置I「M在我的測試方面的文件丟失。單元測試REST控制器與彈簧測試mvc
我沒有得到任何錯誤。我知道它不工作的原因是因爲Hello World
永遠不會被打印(見控制器)。我缺少什麼嗎?
控制器:
@Controller
@RequestMapping("/debug")
public class DebugOutputController {
@RequestMapping(method = RequestMethod.POST)
public void saveDebugOutput(@RequestBody DebugOutput debugOutput, HttpServletResponse response) {
System.out.println("Hello World");
}
}
測試類:
@RunWith(SpringJUnit4ClassRunner.class) //this lets tests access Spring beans defined in the context config file
@ContextConfiguration(locations={"file:src/test/resources/itest/restAPITestContext.xml"}) //tells the test where to get configuration and beans to be used by the test.
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class}) //overrides the default stack of listeners
public class ITRestAPI{
@Autowired
private DebugOutputController debugOutputController;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(debugOutputController).build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void shouldPerformPost() throws Exception {
this.mockMvc.perform(post("/debug"));
}
}
個
restAPITestContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<context:component-scan resource-pattern="*DebugOutputController*" base-package="com.company.project.servlet" />
</beans>
spring-test-mvc確實很有前途,但缺少文檔。在這一點上你知道除README之外的任何內容嗎? –
@MikePartridge我發現的關於它的所有信息都來自他們的Github網站。 –