【问题标题】:Unit Testing - Spring Boot App单元测试 - Spring Boot 应用程序
【发布时间】:2017-01-30 02:56:02
【问题描述】:

我查看了这个链接:How to write a unit test for a Spring Boot Controller endpoint

我计划对我的 Spring Boot 控制器进行单元测试。我从下面的控制器中粘贴了一个方法。当我使用上面链接中提到的方法时,我必须调用 service.verifyAccount(request) 吗?除了测试 HTTP 状态码,我们是否只是测试控制器是否接受指定格式的请求并返回指定格式的响应?

@RequestMapping(value ="verifyAccount", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<VerifyAccountResponse> verifyAccount(@RequestBody VerifyAccountRequest request) {

    VerifyAccountResponse response = service.verifyAccount(request);

    return new ResponseEntity<VerifyAccountResponse>(response, HttpStatus.OK);
}

【问题讨论】:

  • 这取决于你是否模拟了服务对象。如果你没有模拟,它会调用服务。
  • 谢谢@notionquest。 MockMvc 的目的是什么,如果我不使用模拟对象,我的所有依赖项都会通过使用另一篇文章中的代码(已接受的答案)注入吗?
  • 也许这篇stackoverflow.com/questions/32223490/… 的帖子有助于回答您的“MockMvc 的目的是什么”的问题。

标签: unit-testing spring-boot


【解决方案1】:

你可以编写单元测试用例 使用

@RunWith(SpringJUnit4ClassRunner.class)
    // Your spring configuration class containing the                            
  @EnableAutoConfiguration
    // annotation
    @SpringApplicationConfiguration(classes = Application.class)
    // Makes sure the application starts at a random free port, caches it         throughout
    // all unit tests, and closes it again at the end.
    @IntegrationTest("server.port:0")
    @WebAppConfiguration

确保配置所有服务器配置,例如端口/url

 @Value("${local.server.port}")
 private int port;


private String getBaseUrl() {
    return "http://localhost:" + port + "/";
}

然后使用下面提到的代码

        protected <T> ResponseEntity<T>  getResponseEntity(final String       
  requestMappingUrl, final Class<T> serviceReturnTypeClass, final Map<String, ?>       
  parametersInOrderOfAppearance) {
    // Make a rest template do do the service call
    final TestRestTemplate restTemplate = new TestRestTemplate();
    // Add correct headers, none for this example

    final HttpEntity<String> requestEntity = new HttpEntity<String>(new       
  HttpHeaders());
    // Do a call the the url
    final ResponseEntity<T> entity = restTemplate.exchange(getBaseUrl() +       
  requestMappingUrl, HttpMethod.GET, requestEntity, serviceReturnTypeClass,       
  parametersInOrderOfAppearance);
    // Return result
    return entity;
    }

@Test
public void getWelcomePage() {
    Map<String, Object> urlVariables = new HashMap<String, Object>();
    ResponseEntity<String> response = getResponseEntity("/index",     
    String.class,urlVariables);

    assertTrue(response.getStatusCode().equals(HttpStatus.OK));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 2016-10-12
    • 2019-05-18
    • 2019-11-01
    • 2016-05-28
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多