Writing the test case for a singleton

Now let's write a test class to verify the singleton class.

Consider the following test case:

  @Test
public void testSingletonObject() {
Singleton singleton = Singleton.getInstance ();
Singleton anotherSingleton = Singleton.getInstance ();

System.out.println (singleton);
System.out.println (anotherSingleton);
System.out.println (singleton == anotherSingleton);

Assert.assertEquals (singleton,anotherSingleton);
}

In this case, we are trying to instantiate the singleton class twice. We print the two instance objects that are initialized. Since the same object is returned every time the getInstance() function is invoked, it prints the same memory address at which these instances are loaded. The comparison of the instances is evaluated to true as it is the same instance:

Let's add another test case where we invoke a function on the singleton instance:

  @Test
public void testSingleton() {
Singleton singleton = Singleton.getInstance ();
Assert.assertNotNull (singleton);

String details = singleton.getDetails ();
Assert.assertNotNull (details);
Assert.assertEquals ("this is a singleton class", details);
}

In this test case, we initialize the instance by invoking the getInstance() function. On this instance, we call the getDetails() function that is defined in the singleton class. Furthermore, we assert for the non-null value for the instance, followed by the response that is returned from the getDetails() function, and then assert the actual message that is being returned by the function.

Note that the singleton code that we wrote is not thread-safe. If multiple threads access the getInstance() method at the same time, we end up with two instance of the class. To solve this, we use synchronized keywords or static initialization. The synchronized way is lazy initialization and the static initialization is known as eager initialization of the instance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset