如何测试spring controller handler响应

时间:2018-02-23 04:14:46

标签: spring spring-mvc junit

我有弹簧控制器处理程序。我必须使用Junit测试用例来测试该句柄。我是Juint的新手,因此无法测试Junit。我想在eclipse中运行它。

弹簧处理程序:

@Controller  
@RequestMapping("/core")  
public class HelloController  {  
    @RequestMapping(value = "/getEntityType", method = RequestMethod.GET)  
     public ResponseEntity<List<MyEnum >> getEntityType(HttpServletRequest  
 request, HttpServletResponse response) {     
  return new ResponseEntity<List<MyEnum >>(Arrays.asList(MyEnum.values()), HttpStatus.OK);    
        }     

枚举类:

public enum MyEnum {
    FIRST, SECOND, THIRD;
}

测试用例:

@Test
public void testToFindEnumTypes() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "core/getEntityType");
    MockHttpServletResponse response = new MockHttpServletResponse();
    hello.Controller.getEntityType(request, response);
    Assert.assertNotNull(getResponseJSON(response));
}

请告诉我如何为该处理程序运行Junit测试用例。我是Junit测试的新手。

1 个答案:

答案 0 :(得分:0)

从Eclipse开始,应该有一个绿色运行按钮,允许您运行JUnit测试。

Eclipse Help有一篇非常好的文章解释如何: this question

此外,如果在Eclipse外部运行并在maven构建中运行,则需要将junit依赖项添加到maven pom.xml文件中:

<dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
</dependency>

然后按如下方式运行maven test命令:

mvn clean test

此外,您发布的代码中存在一些语法错误。它应该是这样的:

public class HelloControllerTest {

private HelloController helloController = new HelloController();

@Test
public void testToFindEnumTypes() throws Exception {
    // setup
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "core/getEntityType");
    MockHttpServletResponse response = new MockHttpServletResponse();

    // execution
    ResponseEntity actualResponse = helloController.getEntityType(request, response);

    // verify
    assertNotNull(actualResponse);
    assertEquals(HttpStatus.OK, actualResponse.getStatusCode());

    List<MyEnum> myEnumList = (List<MyEnum>) actualResponse.getBody();
    assertTrue(myEnumList.contains(MyEnum.FIRST));
    assertTrue(myEnumList.contains(MyEnum.SECOND));
    assertTrue(myEnumList.contains(MyEnum.THIRD));

}

理想情况下,您还应该正确验证所有返回值,就像我在上面的示例中所做的那样。