Recently started to switch to Java programming, the project is using the JUNIT4 framework. In the case of Java code implemented with Singleton mode (a Hungry man), how do you simulate the methods in this class? Because all common methods in this pattern invoke a common method in the class by getting a static private instance of the class, this requires a static private instance object for that class to be emulated. Research has found that you can use the Whitebox class to help us emulate the static private instance object.
Java source code:
public class HelloWorld {
private static HelloWorld instance = new HelloWorld();
private HelloWorld() {}
public static HelloWorld getInstance() {return instance;}
public void say() {
System.out.println("Hello World!");
}
}
public class HelloWorld {
private static HelloWorld instance = new HelloWorld();
private HelloWorld() {}
public static HelloWorld getInstance() {return instance;}
public void say() {
System.out.println("Hello World!");
}
}
Test code:
public class HelloWorldAppTest {
private HelloWorldApp helloWorldApp;
@Before
public void setUp() throws Exception {
helloWorldApp = new HelloWorldApp();
}
@Test
public void sayHelloWorld() throws Exception {
HelloWorld instanceMock = PowerMockito.mock(HelloWorld.class);
Whitebox.setInternalState(HelloWorld.class, "instance", instanceMock);
Mockito.doNothing().when(instanceMock).say();
helloWorldApp.sayHelloWorld();
Mockito.verify(instanceMock).say();
}
}
Note that "Org.powermock.reflect.whitebox" must be used, and detailed usage of the class can be referred to Http://static.javadoc.io/org.powermock/powermock-reflect /1.6.4/org/powermock/reflect/whitebox.html
Cannot use "Org.mockito.internal.util.reflection.Whitebox", this class does not support impersonation of private fields.
How to mock a Java singleton pattern