What if your singleton performed operations on a database or wrote data to a file? You do not want this to happen in unit test. You would like to mock an object to perform some operations in memory instead, so that you can test them without constant side effects. Unit tests must be self-contained and must not create database connections or perform other operations with external systems that may fail, and then cause your unit test to fail for another reason.
An example with pseudo-java (I am a C # developer):
public class MySingleton { private static final MySingleton instance = new MySingleton(); private MySingleton() { } public int doSomething() {
To test myMethod , we need to make the actual database call, work with the file, etc.
@Test public void testMyMethod() { OtherClass obj = new OtherClass();
If instead of MySingleton there was something like:
public class MyNonSingleton implements ISomeInterface { public MyNonSingleton() {} @Override public int doSomething() {
you can embed it as a dependency in MyOtherClass as follows:
public class OtherClass { private ISomeInterface obj; public OtherClass(ISomeInterface obj) { this.obj = obj; } public int myMethod() {
then you can test as follows:
@Test public void TestMyMethod() { OtherClass obj = new OtherClass(new MockNonSingleton());
source share