Tuesday 6 July 2021

Junit5: Test Instance Lifecycle

Junit creates a new instance of Test class before calling each test method (This is the standard default life cycle mode PER_METHOD). This is the default behaviour is junit Jupiter 5.

 

TestInstanceLifeCycleDemo1.java

package com.sample.app;

import org.junit.jupiter.api.Test;

public class TestInstanceLifeCycleDemo1 {

	@Test
	public void test1() {
		System.out.println("this: " + this);
	}
	
	@Test
	public void test2() {
		System.out.println("this: " + this);
	}
	
	@Test
	public void test3() {
		System.out.println("this: " + this);
	}
}

 

When you ran above test class, you will see below messages in console.

this: com.sample.app.TestInstanceLifeCycleDemo1@3d99d22e
this: com.sample.app.TestInstanceLifeCycleDemo1@131276c2
this: com.sample.app.TestInstanceLifeCycleDemo1@26aa12dd

 

As you observe the output, three different instances created (One instance for one test method).

 

How can I customize this behaviour, so that only one instance is used across all the test methods?

Annotate your test class with @TestInstance(Lifecycle.PER_CLASS)

 

Example

@TestInstance(Lifecycle.PER_CLASS)
public class TestInstanceLifeCycleDemo2 {
	.....
	.....
}

 

TestInstanceLifeCycleDemo2.java

package com.sample.app;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;

@TestInstance(Lifecycle.PER_CLASS)
public class TestInstanceLifeCycleDemo2 {
	@Test
	public void test1() {
		System.out.println("this: " + this);
	}
	
	@Test
	public void test2() {
		System.out.println("this: " + this);
	}
	
	@Test
	public void test3() {
		System.out.println("this: " + this);
	}
}

 

Run above class, you will see below messages in console.

this: com.sample.app.TestInstanceLifeCycleDemo2@3a883ce7
this: com.sample.app.TestInstanceLifeCycleDemo2@3a883ce7
this: com.sample.app.TestInstanceLifeCycleDemo2@3a883ce7

As you observe the console output, you can observe same instance is used in all the test methods.

 

How can I apply ‘Lifecycle.PER_CLASS’ to all my test classes?

You can achieve this in either of following approaches.

 

Approach 1: Set the property 'junit.jupiter.testinstance.lifecycle.default' to 'per_class' in src/test/resources/junit-platform.properties file.

junit.jupiter.testinstance.lifecycle.default = per_class

 

Approach 2: Start JVM with following system property.

-Djunit.jupiter.testinstance.lifecycle.default=per_class


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment