1

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

Anna Klein
  • 1,906
  • 4
  • 27
  • 56
  • 2
    This might answer the first question at least: https://martinfowler.com/bliki/JunitNewInstance.html and a couple of links regarding your second question: https://stackoverflow.com/questions/12087959/junit-run-set-up-method-once, https://www.guru99.com/junit-test-framework.html, https://junit.org/junit5/docs/snapshot/user-guide/#writing-tests-annotations, https://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall – Thomas Nov 22 '22 at 07:36

1 Answers1

1

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.

rodpold
  • 156
  • 6