Skip to content
Advertisement

Sharing an Object between two Test classes in either JUnit or TestNG

Forgive the elementary question, I am learning Java still so need some advice on best practice here. I have a valid scenario where I wish to share the same object between two distinct Test classes using JUnit or TestNG. I understand that tests/test classes should not usually share state but this is a long-running journey.

I understand the JVM executes for both frameworks in this order:

  1. @BeforeClass
  2. Construcor call
  3. @Before
  4. @Test

Given I have an Person class with one field name and one getter & setter for same and I instantiate an instance of it in one Test Class:

JavaScript

And a second Test class:

JavaScript

What is the optimal way of accessing the firstPerson object in the second class? I don’t want to instantiate it a second time because I wish to share state for a journey test.

I want to be able to pass firstPerson instance in the constructor or an annotated setup method, but don’t wish to instantiate the SecondPersonTest within the body of FirstPersonTest

Advertisement

Answer

You can use a singleton class for this purpose.

JavaScript

You can store the whole Person object or only the name field of the Person object.

To store:

JavaScript

To get it back:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement