How to mock a class that calls a singleton class using junit

I would like to test a method from class1 that calls the getInstance singleton class:

 Class ivDomain { public String method1() { id=Singleton.getInstance().generateId() ... code } } 

When I run a test using Junit, I get a NullPointerException in a singleton class. How can i fix this?

+4
source share
4 answers

Classes using statically available singletones are a pain for testing. Modify the ivDomain class to quickly take a singleton instance as a parameter for its constructor, and then fix it as usual. You should use the Injection Dependency framework (e.g. Guice ) to facilitate this development style.

+4
source

You should not scoff at Singleton; just change the code so getInstance() does not return null.

+1
source

The most likely reason - without examining your Singleton code - is that initialization does not allow some external configuration to be loaded and therefore fails.

Singlets in tests of an automatic device can be a problem, because sometimes you like that they behave differently for the particular scenario that you are testing (for example, you want one scenario where generateId returns -1, the other when it returns 4354353 and the other, when he throws a RuntimeException so that you can see how the code using Singleton RuntimeException is recommended to change the design in such cases, since the singletones are not the preferred design patterns and are somewhat considered as anti-shablo us.

+1
source

All Articles