I've noticed the behavior within my unit tests that final fields are reloaded, actually the whole class does so (hashcode of it changes)
Example:
class SomeTest {
private final String aRandomString = RandomStringUtils.randomAlphabetic(10);
@Test
void a() {
}
@Test
void b() {
}
}
aRandomString
changes for method a and b.
Why is that and is there a way to prevent this? (my question is more theoretical right now without a particular use case atm)
My POM has only these test dependencies:
<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 a lot in advance
CodePudding user response:
because the default TestInstance lifecycle is PER_METHOD.
that mean is your every test method are have each Instace.
so fast answer is add TestInstance annotation.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class yourTest {
...
}
but this solution have to be careful not to violate FIRST unit testing principles.