I need to test some legacy code, which uses a singleton in a a method call. The purpose of the test is to ensure that the clas sunder test makes a call to singletons method.
I just want to complete the solution from noscreenname. The solution is using PowerMockito. Because PowerMockito can do something like Mockito, So sometimes you can just use PowerMockito .
The example code is here:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Field;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Singleton.class})
public class SingletonTest {
@Test
public void test_1() {
// create a mock singleton and change
Singleton mock = mock(Singleton.class);
when(mock.dosth()).thenReturn("succeeded");
System.out.println(mock.dosth());
// insert that singleton into Singleton.getInstance()
PowerMockito.mockStatic(Singleton.class);
when(Singleton.getInstance()).thenReturn(mock);
System.out.println("result:" + Singleton.getInstance().dosth());
}
}
Singleton class:
public class Singleton {
private static Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
public String dosth() {
return "failed";
}
}
Here is my Gradle:
/*
* version compatibility see: https://github.com/powermock/powermock/wiki/mockito
*
* */
def powermock='2.0.2'
def mockito='2.8.9'
...
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
/** mock **/
testCompile group: 'org.mockito', name: 'mockito-core', version: "${mockito}"
testCompile "org.powermock:powermock-core:${powermock}"
testCompile "org.powermock:powermock-module-junit4:${powermock}"
testCompile "org.powermock:powermock-api-mockito2:${powermock}"
/**End of power mock **/
}