I have a singleton class that I would like to mock static methods from, so I can test the functionality of the rest of the class. I have created a simpler example to demonstrate. Assume my class that I want to test is this:
public class MockExample {
private static MockExample instance = null;
private static String ourString = "String from main class";
private MockExample() {
}
public static MockExample getInstance() {
if (instance == null) {
instance = new MockExample();
}
return instance;
}
public String getString() {
return getClassString();
}
private static String getClassString() {
return ourString;
}
}
I am trying to mock out MockExample.getClassString() call, my replacing the method with PowerMockito inside the test. It is important to note that that method is private and only gets called through getString(). My test code, with my static mock is below:
public class MockExample {
private static MockExample instance = null;
private static String ourString = "String from main class";
private MockExample() {
}
public static MockExample getInstance() {
if (instance == null) {
instance = new MockExample();
}
return instance;
}
public String getString() {
return getClassString();
}
public static String getClassString() {
return ourString;
}
}
Online examples suggest that if i get the singleton class after I use PowerMockito.replace(method, stub), than it should call the stub. But in this case it is still calling the original method. I have also tried to "spy", but that is proving to be difficult, since my actual code that I need to mock has arguments. PowerMockito.method() handles those well.
Any help would be greatly appreciated. Thank you.