Is it a violation if I go ahead with utility methods as static rather than depending on DI of spring?
I just have to maintain a hashmap like below:
private static Map<String,JMSMessage> messageMap = Collections.synchronizedMap(new HashMap<String,JMSMessage>());
messageMap can be accessed by multiple threads. I have utility methods to play around messageMap. I made my class as final and declared all utility methods as static. Is it a violation according to spring IoC?
I would argue that, even though it is possible and will work correctly in Spring IOC, it is a violation of the principals of inversion-of-control.
It would be better to use a singleton bean that is managed by your IOC than use a static field, like this
#Component
#Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class SimpleMessageManager implements MessageManager {
private Map messageMap = Collections.synchronizedMap(new HashMap());
#Override
void addMessage(...) { ... }
#Override
void getMessage(...) { ... }
}
You could then inject your MessageManager like this:
public class SomeBean {
#Resource
MessageManager messageManager;
}
There are many reasons why sticking to the IOC approach is better:
You may need more than one instance in future.
You can mock out the MessageManager interface in unit tests.
(Related to 2) If you use a static fields, you cannot be sure of the state of the messageMap during testing. This becomes even more complicated if you start running your tests in parallel (a standard option in Maven)
As an aside, I would recommend that you not use Collections.synchronizedMap. Have you considered using ConcurrentHashMap instead?
No it is not a violation against spring because the variable is static. Static variables are only accessible through class name. Spring IoC is useful when you want to remove dependency from the implementation, so that it can change later on without affecting anything else. In case of static variables and methods you have no choice but to access them through their class name.
And remember static variables and methods cannot be overriden.
Related
I have a simple URL builder class with a method that gets a field value from properties via #Value annotation.
#Getter
#Component
public class UrlBuilder {
#Value("${url.api}")
private String apiUrl;
#Value("${url.auth}")
private String authUrl;
public String buildApiUrl(String urlAppendix, Map<String, String> queryParams){
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(apiUrl + urlAppendix);
if (!isEmpty(queryParams)){
for (String key : queryParams.keySet()){
builder.queryParam(key, queryParams.get(key));
}
}
return builder.toUriString();
}
}
Is there a good reason to make the method static and use setter value injection on a static field? So far I had the UrlBuilder being injected via constructor.
Static fields and static injection are an anti-pattern in general, since they amount to global shared state, and create ordering dependencies and occasionally thread-safety issues. (It's hard to ensure that callers never call the buildApiUrl method before static injection takes place.) This is especially true if you're considering using a non-static setter method to set this static field, because that means that calling the setter on one instance will implicitly modify every other instance as well. It's a confusing API; clients will make assumptions based on common practice, and won't notice that their assumptions are wrong unless they really scrutinize the code.
The main reason to consider using a static field is if you have legacy code that isn't integrated with the dependency injection framework. In that sort of situation, you may need to work around the mismatch by creating singleton adapters that forward calls from static methods to dependency-injected beans. But you'll want to do as little of that as you can get away with; it's better to migrate legacy code to use dependency injection, when possible, than to migrate legacy code to use awkward static adapters around dependency injection.
I would never suggest creating static methods in spring bean classes, usually in spring framework until creating util classes i would not recommend static methods.
When to use static methods in Java?
The code in the method is not dependent on instance creation and is not using any instance variable.
A particular piece of code is to be shared by all the instance methods.
The definition of the method should not be changed or overridden.
you are writing utility classes which should not be changed.
I would say you don't need any iteration or util method here, just use the spring MultiValueMap
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("A", "B");
map.add("C", "D");
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://localhost:8080");
builder.queryParams(map); //http://localhost:8080?A=B&C=D
What is the standard approach/best practice to creating variables that are program- or package-wide in Java?
I want to set up some global variables that are accessible by multiple classes. Examples of these global variables would be things like a boolean flag testModeOn, a language setting, current local server, time display format, etc. According to some other questions (namely this one) there aren't any global variables, but there are some work-arounds using interfaces (not recommended?) or classes. Since the original poster didn't explain their situation, they got nearly every answer under the sun and I want to ask specifically for program configuration variables.
Is it better to create a class/package/interface and then import it into my working class/package? Is there anything I should be aware of when trying to implement these variables using a separate class or interface? Is there any other way to fudge package-level variables since Java apparently doesn't do this natively?
NOTE: These variables would probably not change except when the program is re-compiled.
If you're talking about constants, then they should be declared as static final fields in a class (never in an interface, according to Joshua Bloch).
If you're talking about settings which can change on the fly, then these could be either static fields in a class, or you could create a ConfigHandler class to manage the setting and fetching of configurable values.
Using class fields for mutable values might lead to concurrency problems, so if your application is multi-threaded it might be better to create a ConfigHandler class which manages concurrent access carefully and provides synchronized methods to avoid problems.
In my opinion, the best approach to passing anything into your classes is using dependency injection. This would eliminate your need for Singletons, static constants and the likes.
Depending on which DI you favor, here are some link solutions to the problem you describe:
CDI
Spring
Guice
Create a Bean class if multiple variables are required to be used in different classes. Best practice is to create a private variable with its getters and setters.
public class ListBean implements Serializable
{
private boolean testModeOn;
public boolean getTestModeOn()
{
return testModeOn;
}
public setTestModeOn(boolean testModeOn)
{
this.testModeOn = testModeOn;
}
In general there are so many ways to do it wrong regarding this topic.
The simple way is to use a Singelton.
This is not an option - Singelton is an Anti-Pattern. http://c2.com/cgi/wiki?SingletonsAreEvil
So what is else there? An Interface with public static final variables?
Not an option - Thats simply not the use case of an interface: https://stackoverflow.com/a/2659740/1248724
so what is else there?
The answer is:
What I prefer is the spring boot way (e.g. Dependency Injection)
Here an code example which is obviously Spring.
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*
#Component
public class MyBean {
#Value("${name}")
private String name;
// ...
}
If you are using some similar Framework such things could be easy archived.
If that is somehow not possible in your environment I had to code something like this:
public final class Configuration {
private Configuration() {
// make sure there is no instance of this class
}
public static final MySetting<DateFormat> setting = new SampleProperty();
public interface MySetting<T> {
T get();
}
private static final class SampleProperty implements MySetting<DateFormat> {
#Override
public DateFormat get() {
return new SimpleDateFormat("...");
}
}
// other inner classes that implement the MySetting interface
}
public static void main(final String[] args) {
Configuration.setting.get();
}
Benefits:
- You can validate your properties how ever you want.
- You can work with the java security manager if you like to
Downsides:
- You may have to maintain a bunch of code (this should be easier with lambda expressions)
- Not that great as the way spring offers here for example.
A very similar approach I just found: https://stackoverflow.com/a/3931399/1248724
I have an encryption utility method that relies on an external dependency --- a cipher key which is being retrieved from a property file. The way it can be retrieved in the current code base which I inherited is that it relies on creating new objects to be able to get the value of a property in the properties file. For example, if wanted to get the Cipher Key from the property file, it would be like this:
public synchronized static String encrypt(String someTextToEncrypt) {
String propertyValue = null;
propertyValue = getProcessCommonBase().
getProcessProperties.getProperty("CIPHER_KEY");
/*encrypt algorithm*/
return encryptedForm;
}
private synchronized static ProcessCommonBase getProcessCommonBase() {
if (processCommonBase == null) {
processCommonBase = new ProcessCommonBase();
}
return processCommonBase;
}
private static ProcessCommonBase processCommonBase;
EDITED: Design-wise is having a something like the processCommonBase instance variable a good practice to do? My understanding is that a good practice is that static variables should be final and do not change. In this case, however, the ProcessCommonBase class maintains state and is subject to change.
NEW QUESTION: If the static method relies on something external shouldn't I just mark the method and the processCommon base variable as non static and in Spring, just make a bean definition for it? What is better?
I agree with Joonas. I don't see why not make the variable final. Could you elaborate please what exactly do you mean by this:
My understanding is that a good practice is that static variables should be final and do not change. In this case, however, the ProcessCommonBase class maintains state and is subject to change.
Even if the variable is final, you still can change the object it references to in exactly the same ways as you'd do it with a non-final variable. That's why it's perfectly fine for a static method to have a static variable maintaining its state, but nothing stops you from actually making it final in this case. Why not do this:
private static ProcessCommonBase processCommonBase = new ProcessCommonBase();
Maybe there's something stopping you from creating processCommonBase at static initialization time, but it isn't obvious from the information you have provided.
Someone already commented your specific case, but in general, what you described is an effectively final static variable, which is just created "lazily" (that is, only when needed). It's a fine approach, if creating a ProcessCommonBase instance is an expensive and rare event, although you must be careful to access it only via the getter method then. On the other hand, if a ProcessCommonBase will be created whenever the surrounding class is used, then making it actually final is a better approach: it's simpler (less error prone, as you don't need to remember to use the getter method exclusively), and will actually be a bit cheaper, as the final variable is initialized only when the surrounding class is first used, and you don't need the (synchronized!) null check every time when accessing it (of course, if you use > 1 threads andProcessCommonBase isn't thread-safe, then you need to synchronize somewhere).
Answer to your second question: being static vs. not and relying on some external system properties are two separate things. I don't know what Spring does, but if your method essentially a function - "value in, result out" - then it's a static method by its nature, even if it reads its configuration from some system property. Making such methods instance methods is possible, but if it only complicates things and gives nothing, why bother?
The usage of static is often frowned upon from an OO design perspective because it gives tight coupling between objects. With statics methods it’s impossible to decouple an interface from its actual implementation. This lack of decoupling can for example become a problem when you want to unit test a single class, as it can’t be separated from the other static parts.
In today’s Java landscape you’re singleton crypt class can be much better designed with the help of Dependency Injection (DI). The ProcessCommonBase could also be implemented as an DI singleton if it didn’t had that very strong code smell, because if it’s a god-object then it should be refactored, for example by using DI for injecting properties into you crypt class.
Example code based on Google Guice:
#Singleton
public MyCrypt {
private final key;
#Inject
MyCrypt(#CipherKey String key) {
this.pBase = pBase;
}
public synchronized String encrypt(String someTextToEncrypt) {
/*encrypt algorithm*/
return encryptedForm;
}
}
Configuring DI properties:
public class PropertiesModule extends AbstractModule {
#Override
protected void configure() {
String key = .. what ever ..
bind(String.class).annotatedWith(CiperKey.class).toInstance(key);
}
More DI examples can be found here:
http://java.dzone.com/articles/cdi-overview-part-1
Populair Java DI implementations are: Guice, Spring and Java EE6.
I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can implement Singleton Design Patterns.
He seems to be half satisfied with the answer but I want to know
How many different ways we can
implement Singleton Design Pattern
in Java ?
What is the scope of Singleton Object and how does it actually work inside JVM ? I know we would always have one instance of Singleton Object but what is the actual scope of that object, is it in JVM or if there are multiple application running than it's scope is per context basis inside the JVM, I was really stumped at this and was unable to give satisfying explanation ?
Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
Any inputs would be highly appreciated about Singleton and what are the main things to keep in mind while dealing with Singletons ?
Thanks.
There are a few ways to implement a Singleton pattern in Java:
// private constructor, public static instance
// usage: Blah.INSTANCE.someMethod();
public class Blah {
public static final Blah INSTANCE = new Blah();
private Blah() {
}
// public methods
}
// private constructor, public instance method
// usage: Woo.getInstance().someMethod();
public class Woo {
private static final Woo INSTANCE = new Woo();
private Woo() {
}
public static Woo getInstance() {
return INSTANCE;
}
// public methods
}
// Java5+ single element enumeration (preferred approach)
// usage: Zing.INSTANCE.someMethod();
public enum Zing {
INSTANCE;
// public methods
}
Given the examples above, you will have a single instance per classloader.
Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?
Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".
I disagree with #irreputable.
The scope of a Singleton is its node in the Classloader tree. Its containing classloader, and any child classloaders can see the Singleton.
It's important to understand this concept of scope, especially in the application servers which have intricate Classloader hierarchies.
For example, if you have a library in a jar file on the system classpath of an app server, and that library uses a Singleton, that Singleton is going to (likely) be the same for every "app" deployed in to the app server. That may or may not be a good thing (depends on the library).
Classloaders are, IMHO, one of the most important concepts in Java and the JVM, and Singletons play right in to that, so I think it is important for a Java programmer to "care".
I find it hard to believe that so many answers missed the best standard practice for singletons - using Enums - this will give you a singleton whose scope is the class loader which is good enough for most purposes.
public enum Singleton { ONE_AND_ONLY_ONE ; ... members and other junk ... }
As for singletons at higher levels - perhaps I am being silly - but my inclination would be to distribute the JVM itself (and restrict the class loaders). Then the enum would be adequate to the job .
Singleton is commonly implemented by having a static instance object (private SingletonType SingletonType.instance) that is lazily instantiated via a static SingletonType SingletonType.getInstance() method. There are many pitfalls to using singletons, so many, in fact, that many consider singleton to be a design anti-pattern. Given the questions about Spring, the interviewer probably was looking for an understanding not only of singletons but also their pitfalls as well as a workaround for these pitfalls known as dependency injection. You may find the video on the Google Guice page particularly helpful in understanding the pitfalls of singletons and how DI addresses this.
3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
a static field can have multiple occurrences in one JVM - by using difference class loaders, the same class can be loaded and initialized multiple times, but each lives in isolation and JVM treat the result loaded classes as completely different classes.
I don't think a Java programmer should care, unless he's writing some frameworks. "One per VM" is a good enough answer. People often talk that way while strictly speaking they are saying "one per classloader".
Can we have one singleton per cluster? Well that's a game of concepts. I would not appreciate an interviewer word it that way.
There's the standard way, which you already covered. Also, most dependency-injection schemes have some way to mark a class as a singleton; this way, the class looks just like any other, but the framework makes sure that when you inject instances of that class, it's always the same instance.
That's where it gets hairy. For example, if the class is initialized inside a Tomcat application context, then the singleton instance's lifetime is bound to that context. But it can be hard to predict where your classes will be initialized; so it's best not to make any assumptions. If you want to absolutely make sure that there's exactly one instance per context, you should bind it as an attribute of the ServletContext. (Or let a dependency-injection framework take care of it.)
--
Not sure I understand the question - but if you're talking about having a singleton instance that's shared between several cluster nodes, then I think EJB makes this possible (by way of remote beans), though I've never tried it. No idea how Spring does it.
Singleton is a creational pattern and hence governs object instantiation. Creating singletons would mandate that you voluntarily or involuntarily give up control on creating the object and instead rely on some way of obtaining access to it.
This can be achieved using static methods or by dependency injection or using the factory pattern. The means is immaterial. In case of the normal protected constructor() approach, the consumer perforce needs to use the static method for accessing the singleton. In case of DI, the consumer voluntarily gives up control over the instantiation of the class and instead relies on a DI framework to inject the instance into itself.
As pointed out by other posters, the class loader in java would define the scope of the singleton. Singletons in clusters are usually "not single instances" but a collection of instances that exhibit similar behavior. These can be components in SOA.
The Following Code is from here
The Key point is you should Override the clone method...The Wikipedia example also is helpful.
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Query 1:
Different ways of creating Singleton
Normal Singleton : static initialization
ENUM
Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton
Have a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.
Singleton is a creational design pattern.
Intents of Singleton Design Pattern :
Ensure a class has only one instance, and provide a global point of
access to it.
Encapsulated "just-in-time initialization" or "initialization on
first use".
I'm showing three types of implementation here.
Just in time initialization (Allocates memory during the first run, even if you don't use it)
class Foo{
// Initialized in first run
private static Foo INSTANCE = new Foo();
/**
* Private constructor prevents instantiation from outside
*/
private Foo() {}
public static Foo getInstance(){
return INSTANCE;
}
}
Initialization on first use (or Lazy initialization)
class Bar{
private static Bar instance;
/**
* Private constructor prevents instantiation from outside
*/
private Bar() {}
public static Bar getInstance(){
if (instance == null){
// initialized in first call of getInstance()
instance = new Bar();
}
return instance;
}
}
This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com
class Blaa{
/**
* Private constructor prevents instantiation from outside
*/
private Blaa() {}
/**
* BlaaHolder is loaded on the first execution of Blaa.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class BlaaHolder{
public static Blaa INSTANCE = new Blaa();
}
public static Blaa getInstance(){
return BlaaHolder.INSTANCE;
}
}
I recently read that making a class singleton makes it impossible to mock the objects of the class, which makes it difficult to test its clients. I could not immediately understand the underlying reason. Can someone please explain what makes it impossible to mock a singleton class? Also, are there any more problems associated with making a class singleton?
Of course, I could write something like don't use singleton, they are evil, use Guice/Spring/whatever but first, this wouldn't answer your question and second, you sometimes have to deal with singleton, when using legacy code for example.
So, let's not discuss the good or bad about singleton (there is another question for this) but let's see how to handle them during testing. First, let's look at a common implementation of the singleton:
public class Singleton {
private Singleton() { }
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
public String getFoo() {
return "bar";
}
}
There are two testing problems here:
The constructor is private so we can't extend it (and we can't control the creation of instances in tests but, well, that's the point of singletons).
The getInstance is static so it's hard to inject a fake instead of the singleton object in the code using the singleton.
For mocking frameworks based on inheritance and polymorphism, both points are obviously big issues. If you have the control of the code, one option is to make your singleton "more testable" by adding a setter allowing to tweak the internal field as described in Learn to Stop Worrying and Love the Singleton (you don't even need a mocking framework in that case). If you don't, modern mocking frameworks based on interception and AOP concepts allow to overcome the previously mentioned problems.
For example, Mocking Static Method Calls shows how to mock a Singleton using JMockit Expectations.
Another option would be to use PowerMock, an extension to Mockito or JMock which allows to mock stuff normally not mock-able like static, final, private or constructor methods. Also you can access the internals of a class.
The best way to mock a singleton is not to use them at all, or at least not in the traditional sense. A few practices you might want to look up are:
programming to interfaces
dependency injection
inversion of control
So rather than having a single you access like this:
Singleton.getInstance().doSometing();
... define your "singleton" as an interface and have something else manage it's lifecycle and inject it where you need it, for instance as a private instance variable:
#Inject private Singleton mySingleton;
Then when you are unit testing the class/components/etc which depend on the singleton you can easily inject a mock version of it.
Most dependency injection containers will let you mark up a component as 'singleton', but it's up to the container to manage that.
Using the above practices makes it much easier to unit test your code and lets you focus on your functional logic instead of wiring logic. It also means your code really starts to become truly Object Oriented, as any use of static methods (including constructors) is debatably procedural. Thus your components start to also become truly reusable.
Check out Google Guice as a starter for 10:
http://code.google.com/p/google-guice/
You could also look at Spring and/or OSGi which can do this kind of thing. There's plenty of IOC / DI stuff out there. :)
A Singleton, by definition, has exactly one instance. Hence its creation is strictly controlled by the class itself. Typically it is a concrete class, not an interface, and due to its private constructor it is not subclassable. Moreover, it is found actively by its clients (by calling Singleton.getInstance() or an equivalent), so you can't easily use e.g. Dependency Injection to replace its "real" instance with a mock instance:
class Singleton {
private static final myInstance = new Singleton();
public static Singleton getInstance () { return myInstance; }
private Singleton() { ... }
// public methods
}
class Client {
public doSomething() {
Singleton singleton = Singleton.getInstance();
// use the singleton
}
}
For mocks, you would ideally need an interface which can be freely subclassed, and whose concrete implementation is provided to its client(s) by dependency injection.
You can relax the Singleton implementation to make it testable by
providing an interface which can be implemented by a mock subclass as well as the "real" one
adding a setInstance method to allow replacing the instance in unit tests
Example:
interface Singleton {
private static final myInstance;
public static Singleton getInstance() { return myInstance; }
public static void setInstance(Singleton newInstance) { myInstance = newInstance; }
// public method declarations
}
// Used in production
class RealSingleton implements Singleton {
// public methods
}
// Used in unit tests
class FakeSingleton implements Singleton {
// public methods
}
class ClientTest {
private Singleton testSingleton = new FakeSingleton();
#Test
public void test() {
Singleton.setSingleton(testSingleton);
client.doSomething();
// ...
}
}
As you see, you can only make your Singleton-using code unit testable by compromising the "cleanness" of the Singleton. In the end, it is best not to use it at all if you can avoid it.
Update: And here is the obligatory reference to Working Effectively With Legacy Code by Michael Feathers.
It very much depends on the singleton implementation. But it mostly because it has a private constructor and hence you can't extend it. But you have the following option
make an interface - SingletonInterface
make your singleton class implement that interface
let Singleton.getInstance() return SingletonInterface
provide a mock implementation of SingletonInterface in your tests
set it in the private static field on Singleton using reflection.
But you'd better avoid singletons (which represent a global state). This lecture explains some important design concepts from testability point of view.
It's not that the Singleton pattern is itself pure evil, but that is massively overused even in situations where it is inapproriate. Many developers think "Oh, I'll probably only ever need one of these so let's make it a singleton". In fact you should be thinking "I'll probably only ever need one of these, so let's construct one at the start of my program and pass references where it is needed."
The first problem with singleton and testing is not so much because of the singleton but due to laziness. Because of the convenience of getting a singleton, the dependency on the singleton object is often embedded directly into the methods which makes it very difficult to change the singleton to another object with the same interface but with a different implementation (for example, a mock object).
Instead of:
void foo() {
Bar bar = Bar.getInstance();
// etc...
}
prefer:
void foo(IBar bar) {
// etc...
}
Now you can test function foo with a mocked bar object which you can control. You've removed the dependency so that you can test foo without testing bar.
The other problem with singletons and testing is when testing the singleton itself. A singleton is (by design) very difficult to reconstruct, so for example you can only test the singleton contructor once. It's also possible that the single instance of Bar retains state between tests, causing success or failure depending on the order that the tests are run.
There is a way to mock Singleton. Use powermock to mock static method and use Whitebox to invoke constructor YourClass mockHelper = Whitebox
.invokeConstructor(YourClass.class);
Whitebox.setInternalState(mockHelper, "yourdata",mockedData);
PowerMockito.mockStatic(YourClass.class);
Mockito.when(YourClass.getInstance()).thenReturn(mockHelper);
What is happening is that the Singleton byte code is changing in run-time .
enjoy