Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is a class reloaded with a junit test?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading