I have this code
public final class TestClass {
private final SomeClass someClass;
/**
* Singleton instance.
*/
public static final TestClass DEFAULT = new TestClass();
private TestClass() {
this.someClass = SomeClass.builder()
.field(getFieldFromEnv())) <---- Method that fetches from env variable, or throws exception if not present
.build();
}
public TestClass(SomeClass someClass) {
this.someClass = someClass;
....
}
Now in order to unit test the TestClass and pass in a mock of someClass i had to create the public constructor as above. Now what is happening is that when i am creating the mock in the unit test and passing it in as
@BeforeEach
public void setup() {
mocks = MockitoAnnotations.openMocks(this);
testClass = new TestClass(mockSomeClass);
}
The DEFAULT singleton is getting invoked which is calling getFieldFromEnv) and as the environment variable is not set, is throwing an exception making my test class send failures.
I am wondering if there is a way to have the unit test ignore the DEFAULT constructor exception or simply not create the singleton DEFAULT as it is not needed during unit testing.