[英]How to test spring RESTful MVC controller methods?
I've got simple Spring MVC project created in Spring Tool Suite IDE, so project's structure is 我在Spring Tool Suite IDE中创建了一个简单的Spring MVC项目,因此项目的结构是
I need to test my controller methods, for example 例如,我需要测试我的控制器方法
@RequestMapping(value = "/references/{id}", method = RequestMethod.GET)
public @ResponseBody GAReference getReference(@PathVariable("id") int id) {
return server.getReference(id);
}
server is an interface, it has implementation (ServerTestImpl), and there is a ServerTestImpl bean stored in MainControllerContext.xml. 服务器是一个接口,它具有实现(ServerTestImpl),并且在MainControllerContext.xml中存储有一个ServerTestImpl bean。
I want my test class to look like in this answer , but I don't have springDispatcher-servlet.xml in my project structure. 我希望测试类在此答案中看起来像,但我的项目结构中没有springDispatcher-servlet.xml。 So, I think it might be like
所以,我认为这可能像
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/MainControllerContext.xml")
@WebAppConfiguration
public class MainControllerTest {
private MockMvc mockMvc ;
@Autowired
WebApplicationContext wac;
@Autowired
private ServerTestImpl server;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
}
@Test
public void testGetReference() {
try {
mockMvc.perform(get("/references/5"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].description", is("Lorem ipsum")))
.andExpect(jsonPath("$[0].title", is("Foo")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].description", is("Lorem ipsum")))
.andExpect(jsonPath("$[1].title", is("Bar")));
} catch (Exception e) {
e.printStackTrace();
}
}
}
How can I test my controller with this project structure? 如何使用该项目结构测试我的控制器? Thanks.
谢谢。
By using the org.springframework.web.client.RestTemplate we can test the spring rest/spring-ws applications. 通过使用org.springframework.web.client.RestTemplate,我们可以测试spring rest / spring-ws应用程序。
Try the below code snippet on setup 尝试在安装程序中使用以下代码段
@Before public void setUp($basecontroller controllerobj)
@Before公共void setUp($ basecontroller controllerobj)
{ this.mockMvc = MockMvcBuilders.standAloneSetup(controllerobj).dispatchOptions(true).build();{this.mockMvc = MockMvcBuilders.standAloneSetup(controllerobj).dispatchOptions(true).build(); }
}
$basecontroller = base controller of the controllers residing in the same package as the other controllers. $ basecontroller =与其他控制器位于同一软件包中的控制器的基本控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.