第一个注解@RunWith(SpringRunner.class) 用于在Spring Boot 测试功能和JUnit 之间架起一座桥梁。 SpringRunner.class 完全支持测试中 bean 的 spring 上下文加载和依赖注入。 @SpringBootTest 通过 SpringApplication 创建 ApplicationContext 测试,这些测试将在我们的测试中使用。它引导自嵌入式服务器以来的整个容器并创建一个 Web 环境。
在我们的测试中,我们可以模拟真实的 Web 环境,将其设置为同时加载 WebServerApplicationContext 的 RANDOM_PORT。嵌入式服务器启动并在随机端口上侦听。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {YourPackage.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class YourClassTest {
@LocalServerPort
private int port;
@Autowired
TestRestTemplate restTemplate;
HttpHeaders headers = new HttpHeaders();
@ParameterizedTest
@JsonFileSource(resources = "/param.json")
void createBusinessEntity(JsonObject object){
....
}
}
@LocalServerPort 注释为我们提供了在运行时分配的注入 HTTP 端口。它是@Value("${local.server.port}") 的便捷替代方案。
要访问 Spring 应用程序中的第三方 REST 服务,我们使用 Spring RestTemplate 或 TestRestTemplate 方便的替代方案,通过将其注入到我们的测试类中来进行集成测试。在我们的项目中使用 spring-boot-starter-test 依赖,我们可以在运行时访问“TestRestTemplate”类。
在我们的测试方法中,我们使用了 junit-json-params ,这是一个 Junit 5 库,它提供注释以在参数化测试中从 JSON 字符串或文件加载数据。我们还使用 @ParameterizedTest 注释对该方法进行了注释,以补充下面的库。它用于表示带注释的方法是一种参数化的测试方法。该方法不能是私有的或静态的。他们还必须通过@ArgumentsSource 或相应的组合注解指定至少一个 ArgumentsProvider。
我们的 @ArgumentsSource 是一个 JSON 文件 @JsonFileSource(resources = "param.json") 我们放在 test.resources 包中。 @JsonFileSource 允许您使用类路径中的 JSON 文件。它支持单个对象、对象数组和 JSON 原语。
从文件中检索到的 JSON 对象绑定到方法 params “object”,它被转换为 POJO 对象,在本例中为我们的实体模型。
在 Pom.xml 中我们必须导入这些库...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.joshka</groupId>
<artifactId>junit-json-params</artifactId>
<version>5.5.1-r0</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit-jupiter.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
查看 DZone 和我的博客上的这些文章,您可以在其中访问完整的示例和逐步说明如何使用 Junit 5 测试 Spring Boot 微服务。
https://dzone.com/articles/microservices-in-publish-subscribe-communication-u
https://www.jeevora.com/2019/11/18/publish-subscribe-messaging-systems/