首页 > 解决方案 > 你可以在没有 starter-web 的情况下使用 spring-boot-starter-test 吗?

问题描述

我正在尝试在一个单独的项目中编写集成测试,该项目没有“web”代码只是测试。我试图只添加这样的spring-test-starter:

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.3.4.RELEASE'

无需添加此(或类似的启动器)

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.3.4.RELEASE'

但似乎当我去使用 org.springframework.boot.test.web.client.TestRestTemplate

返回类型不包含在 org.springframework.boot.test 它在“org.springframework.http.ResponseEntity”下

public <T> ResponseEntity<T> getForEntity(String url,
                                          Class<T> responseType,
                                          Map<String,?> urlVariables)
                                   throws RestClientException

我找不到任何地方说 spring-boot-starter-test 取决于说 spring-boot-starter-web 因为否则启动器的意义何在?有没有一种方法可以在不依赖 (2) 启动器的情况下使用 TestRestTemplate?

标签: javaspringspring-bootspring-test

解决方案


如果您不想使用入门包,则需要手动为所需的包添加依赖项。喜欢ResponseEntity是 的一部分spring-web。因此,您需要向您或文件添加spring-web依赖项。pom.xmlbuild.gradle

如果您只想使用 spring-web 进行测试,那么您可以将此行添加到您的 build.gradle 文件中。

testCompile group: 'org.springframework', name: 'spring-web', version: '5.2.9.RELEASE'

或你的 pom.xml 文件

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.9.RELEASE</version>
    <scope>test</scope>
</dependency>

检查您需要的版本。


推荐阅读