Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Singleton instances with JUnit tests

I have a standalone singleton which successfully passes the test. But with a group of tests this fails since once a singleton is defined it does not allow to reset the instance.

Any ideas about how to go about this?

like image 519
kal Avatar asked Jan 30 '10 07:01

kal


People also ask

Can singleton class have multiple instances?

Well-designed singleton can have only one instance per application. Creating of multiple instances is a mistake in the application design. It might happen in some cases, e.g.: Non thread safe singleton with lazy initialization: several threads are trying to get an instance and creates multiple instances.

How many types of singleton are there?

There are two types of singleton implementations: eager and lazy initialization.

Why is singleton not testable?

It's very difficult to write unit tests for code that uses singletons because it is generally tightly coupled with the singleton instance, which makes it hard to control the creation of singleton or mock it.


1 Answers

I assume you have a private static field within your singleton class to store the initialized instance.

If you do not want to modify your code, you can define a teardown method which run after every test, and in this method you set this static field to null via reflection as seen here.

like image 59
Csaba_H Avatar answered Sep 27 '22 19:09

Csaba_H