java - 如何测试 Spring RESTful MVC Controller 方法?

标签 java spring spring-mvc

我在 Spring Tool Suite IDE 中创建了简单的 Spring MVC 项目,因此项目的结构是

enter image description here

例如,我需要测试我的 Controller 方法

    @RequestMapping(value = "/references/{id}", method = RequestMethod.GET)
    public @ResponseBody GAReference getReference(@PathVariable("id") int id) { 
        return server.getReference(id);
    }

server是一个接口(interface),它有实现(ServerTestImpl),并且MainControllerContext.xml中存储有一个ServerTestImpl bean。

我希望我的测试类看起来像 answer 中的样子,但我的项目结构中没有 springDispatcher-servlet.xml 。 所以,我认为可能是这样的

@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();
        }       
    }

}

如何使用此项目结构测试我的 Controller ? 谢谢。

最佳答案

尝试以下设置代码片段

@Before public void setUp($basecontroller controllerobj)
{ this.mockMvc = MockMvcBuilders.standAloneSetup(controllerobj).dispatchOptions(true).build(); }

$basecontroller = 与其他 Controller 位于同一包中的 Controller 的基本 Controller 。

关于java - 如何测试 Spring RESTful MVC Controller 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676077/

相关文章:

Java 编译器认为 byte[] 是 String

java - 使用 Spring 和 Spring Security 正确注入(inject) SessionFactory

java - Spring MVC 3.2.8 : Create a new FileSystemXmlApplicationContext and loading the definitions from the given XML files

spring-mvc - 如何在 Spring MVC Controller 中动态设置内容类型(取决于请求参数的存在)?

hibernate - 组织.apache.tomcat.dbcp.dbcp.SQLNestedException : Cannot load JDBC driver class 'org.postgresql.Driver'

java - 自定义 Jackson HttpMessageConverter 在 Spring 4.2 中不再有效

java - 自动化脚本 : is it possible to find particular text on the screen?

java - 编写依赖于 gems 和 Maven 项目的 JRuby 代码

java - 比较两个 json 结构并得到不匹配的变化

java - 如何在 Debian 服务器上部署 Spring RESTful API?