为什么用junit测试重新加载一个类?



我注意到在我的单元测试中的行为,最终字段被重新加载,实际上整个类都这样做(它的hashcode改变)

的例子:

class SomeTest {

private final String aRandomString  = RandomStringUtils.randomAlphabetic(10);
@Test
void a() {
}
@Test
void b() {
}
}

方法a和b的aRandomString变化

有办法防止这种情况吗?(我的问题现在更理论化,没有一个特定的用例)

我的POM只有这些测试依赖项:

<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Thanks much in advance

因为TestInstance的默认生命周期是PER_METHOD。

这意味着你的每个测试方法都有每个实例。

所以快速的答案是添加TestInstance注释。

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class yourTest {
...
}

但是这个解决方案必须小心不要违反FIRST单元测试原则。

最新更新