【问题标题】:Spring boot 1.4 - REST API TestingSpring Boot 1.4 - REST API 测试
【发布时间】:2017-04-23 21:56:15
【问题描述】:

我想为我的 Spring mvc REST 控制器编写测试。我正在关注https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4 的官方文档,所以刚刚更新了to 1.4 版本,并按照文档的建议添加了spring boot。

我添加了以下依赖项:

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency> 

和父母

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
  </parent>

我想要测试的 LoginController API 如下所示:

@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<HashMap<String, Object>> login() {


          // some logic to get Customer
        return new ResponseEntity<>(customer, HttpStatus.OK);

    }

根据文档,这里是我的测试:

@RunWith(SpringRunner.class)
@WebMvcTest(LoginController.class)
@SpringBootTest
public class AuthorizationAndAuthenticationTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private WebApplicationContext webApplicationContext;
    private LoginController loginController;
    @Autowired
    private TestRestTemplate restTemplate;

    @MockBean
    private LoggingService loggingService;

    @Test
    public void test() {
        given(this.loggingService.logInfoMessage("some Dummy Message", this.getClass())).
        this.restTemplate.getForObject("/login", Object.class);
    }
}

问题: 1. 由于登录控制器使用了许多服务,我想使用 "given" 模拟它们,但它会产生编译问题,似乎我缺少一些依赖项,但不确定。 2.TestRestTemplate 已弃用,有什么替代方案?我没有找到任何替代方案。

这是我第一次使用 Spring 框架编写测试,所以我可能会忽略一些细节。

请帮帮我。

【问题讨论】:

    标签: spring spring-mvc junit spring-boot spring-test-mvc


    【解决方案1】:

    关于问题 #1:您可能在尝试存根 logInfoMessage 时忘记了 to call .withReturn

    given(this.loggingService.logInfoMessage("some Dummy Message", this.getClass()))
       .willReturn("your desired value")
    

    关于问题 #2:org.springframework.boot.test.TestRestTemplate 已被 org.springframework.boot.test.web.client.TestRestTemplate 弃用。

    所以只需更换包装。

    顺便说一句,最适合测试 Spring MVC 端点的构造是 MockMvc 而不是 TestRestTemplate。

    【讨论】:

      猜你喜欢
      • 2016-10-29
      • 2023-03-25
      • 2017-11-02
      • 2019-08-24
      • 2019-07-18
      • 2016-11-28
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多