I am using an enum singleton that looks (somewhat) like this:
public enum mySingleton{
INSTANCE;
private static String myDrink = null;
public String getMyDrink(boolean isWizard)
{
if (myDrink == null)
{
if (isWizard)
myDrink = "Butterbeer";
else
myDrink = "Whiskey";
}
return myDrink;
}
//Some more functionality
//...
}
Now, to test this singleton i have a few tests that use it. But since all the test run one after the other in the same thread, once i run the first test, myDrink is set for all the other tests.
I don’t like that.
I was thinkin of using an @After function and use reflection to do set myDrink to null.
Iv’e tried this:
Field f = mySingleton.class.getField("myDrink");
f.setAccessible(true);
f.set(String.class, null);
But i get a java.lang.NoSuchFieldException.
How can it be done?
The
myDrinkfield shouldn’t be static. Make it a non-static field, and then useAlso, use
getDeclaredFieldinstead ofgetField.getFieldlooks for public fields.If you can’t change it to non-static, then the first argument is ignored, so just use