I am using jmockit version 1.24 with junit5 where I am mocking a public method of a singleton class as shown below.
Here's my Test.java:
@Test
void myTest() {
MockUp mySingletonMock = new MockUp<MySingleton>() {
@Mock
public FileHeaders getHeader(String localFilePath) {
return new FileHeaders(checksum, "", "", new Date());
}
};
// Some assert statements
mySingletonMock.tearDown();
}
And this is Singleton.java:
public class MySingleton {
private static MySingleton instance = new MySingleton();
private MySingleton(){
// Some initialization
}
public static MySingleton getInstance(){
return instance;
}
public FileHeaders getHeader(String localFilePath) {
...
}
}
I am facing a problem with the above approach where all tests that execute after myTest
completes execution fail as they still see the mocked getHeader
method instead of the original one in the MySingleton class (I have verified that this is indeed the case using debug statements).
How to prevent this mocked version of getHeader
method being seen in other tests? (preferably without changing the version of jmockit).
The weird part of all this is that the tests run without any issue locally on my system using maven. But fail when run on teamcity.
Any help is appreciated. Thank you.
Edit: Things I have tried:
I have tried adding the
$clinit()
method to the MockUp. But no luck.I have reset the singleton instance to a new instance through reflection at the end of my test as shown below. This did not solve the problem either.
void resetMySingletonInstance() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Constructor<?>[] constructors = MySingleton.class.getDeclaredConstructors();
Constructor theConstructor = constructors[0];
theConstructor.setAccessible(true);
// Verified that this gives a new instance
MySingleton instanceMySingleton = (MySingleton) theConstructor.newInstance();
Field ourInstanceField = MySingleton.class.getDeclaredField("ourInstance");
ourInstanceField.setAccessible(true);
ourInstanceField.set(null, instanceMySingleton);
}