How to mock a Java singleton pattern

Source: Internet
Author: User


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.