【问题标题】:How to test spring controller handler response如何测试弹簧控制器处理程序响应
【发布时间】:2018-02-23 04:14:45
【问题描述】:

我有弹簧控制器处理程序。我必须使用 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 测试的新手。

【问题讨论】:

  • 您需要提供更多详细信息。你想从哪里运行它? IDE?一个 Maven 构建?您是否遇到特定错误?

标签: spring spring-mvc junit


【解决方案1】:

在 Eclipse 中,应该有一个绿色的运行按钮,允许您运行 JUnit 测试。

Eclipse 帮助中有这篇非常好的文章,解释了如何: https://help.eclipse.org/neon/index.jsptopic=%2Forg.eclipse.jdt.doc.user%2FgettingStarted%2Fqs-junit.htm

另外,如果在 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));

}

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

【讨论】:

  • 非常感谢您的帮助,我真的很感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 2013-06-17
  • 1970-01-01
  • 2022-07-21
  • 2014-11-30
  • 1970-01-01
相关资源
最近更新 更多