Can Guice assert that a singleton is not directly instantiated? - java

Is it possible for Guice throw an exception if I try to construct a new instance of a singleton?
For example:
public class MyModule extends AbstractModule {
#Override
protected void configure() {
bind(MySingleton.class).in(Singleton.class);
}
}
#Singleton
public class MySingleton {
MySingleton() { /* ... */ }
}
public class RightWay {
public void withInjector() {
Injector injector = Guice.createInjector(new MyModule());
MySingleton mySingleton = injector.getInstance(MySingleton.class);
}
}
public class AnotherRightWay {
private final MySingleton mySingleton;
#Inject
public AnotherRightWay(MySingleton mySingleton) {
this.mySingleton = mySingleton;
}
}
public class TheWrongWay {
public void directInstantiation() {
MySingleton mySingleton = new MySingleton(); // I want an exception here!
}
}
By making MySingleton's constructor package private, I can limit the scope for mistakes, but of course classes in the same package can still throw a spanner into the works. The advantage here is that my unit tests for AnotherRightWay can easily pass mocks of MySingleton to its constructor.
Or, I could make MySingleton's constructor protected, which Guice can handle, and I can still mock by making my mocks extend MySingleton. But then a MySingleton user could do the same without knowing the danger.
If Guice can throw an exception, I can use reflection in my unit tests to construct mocks, but my users could not easily accidentally create a non-singleton version of MySingleton.
Is this possible? Should I just use either the package-private or protected and learn to love the bomb?

Guice is not magic. You can't force it to do something outside of an Injector, so no, you can't do that, and in fact you shouldn't.
The best way, as you have already noticed, is to make constructor of MySingleton package-private. That way no one outside of the package will be able to construct it but Guice. Since this package is controlled by you, it is safe assumption that no one will create MySingleton in other way than via Guice (using your module, of course).
This is not a "bomb". Package-private modifier is intended exactly for this purpose. It is assumed that you control your packages, so it is fine to make constructors and other things package-private and assume that no one but you will call them.

Related

Mocking singleton with PowerMockito

in order to test one of the private method I coded, I need to mock a Singleton.
After testing several methods with PowerMockito :
PowerMockito.mockStatic(UtilDatabaseSoldeAutoCdeCommon.class);
Mockito.when(UtilDatabaseSoldeAutoCdeCommon.getInstance()).thenReturn(mockDatabase);
I could never mock this class. Thus I cannot test my methods as in every of them, I access to database.
UtilDatabaseSoldeAutoCdeCommon is defined as such :
public class UtilDatabaseSoldeAutoCdeCommon extends AbstractUtilDatabase {
private static UtilDatabaseSoldeAutoCdeCommon instance;
private UtilDatabaseSoldeAutoCdeCommon() {
super();
}
public static UtilDatabaseSoldeAutoCdeCommon getInstance() {
if(instance == null) {
instance = new UtilDatabaseSoldeAutoCdeCommon();
}
return instance;
}
...
}
I debugged powermockito when it calls getInstance() but everytime consructor is called, it crashes as it tries to load configuration file (which does not exist).
I precise that config file is defined as a constant in absract parent class of UtilDatabaseEnrichissement and used in constructor.
How could I test this part ?
I think this should work:
#PrepareForTest({UtilDatabaseSoldeAutoCdeCommon.class})
public class SomeTest {
#Mock
UtilDatabaseSoldeAutoCdeCommon fakeSingletonInstance;
#Test
public void test() {
Whitebox.setInternalState(UtilDatabaseSoldeAutoCdeCommon.class, "instance", fakeSingletonInstance);
// Write here your test
}
}
This question was asked long time back and I was facing similar issue and unable to find good answers hence answering it now. I tested the class with suppressing constructor like
PowerMockito.suppress(UtilDatabaseSoldeAutoCdeCommon.class.getConstructors());
PrepareForTest the singleton class you mock

Java: getInstance vs Static

What is the purpose of getInstance() in Java?
During my research I keep reading that getInstance() helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?
If I were to just have static methods and fields, how would it differ from using getInstance()? Is there a "scope" of static? For example, one instance per method or class?
And if they are different, in what cases would I choose getInstance() over using static?
I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.
Thank you for any and all advice.
Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.
public class Singleton {
private static Singleton singleton;
private Singleton(){ }
public static synchronized Singleton getInstance( ) {
if (singleton == null)
singleton=new Singleton();
return singleton;
}
}
Check out this top answer: Static Classes In Java
The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html
Singleton
A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
Now we are going to set the value of this number in the A class:
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
Then, you can access this value from another class:
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();
/*...*/
}
In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:
All the values stored in the singleton will be accessible from
"everywhere".
Static class
The purpose is different, here the advantage is to use an object without having to create it.
For example:
public static class MyStaticClass {
public static void sayHello() {
System.out.println("Hello");
}
}
Now you can use the sayHello() method from any classes by calling:
MyStaticClass.sayHello();
The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".
Classes are themselves effectively singletons, so from that aspect they are similar.
The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.
Instances however don't have this problem, so you can code for example:
class MySingleton implements SomeInterface {
...
}
SomeInterface instance = MySingleton.getInstance();
I prefer to use static too, but sometimes getInstance() is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static.
When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance().
Instead of checking for null, I like this a little better.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Called with...
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
}
}
Full code from: http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
One overlooked reason to use a singleton instead of static class member variables is that the static member variables MAY use space and garbage collector time even in the event the class is never instantiated. Consider how many classes are available to you in rt.jar and what a small fraction of them you probably use in any given application. Also consider that using getInstance ensures your "constructor" has run before any of the member variables are accessed. I almost universally see getInstance as synchronized but I feel this is a bad idea. If anyone ever adds a synchronized blocking method calls to Singleton.getInstance().unsynchronized() could be needlessly held up.
private static Singleton instance = null;
private Singleton() {}
public final static Singleton getInstance() {
return (instance != null) ? instance : makeInstance();
}
private final static synchronized Singleton makeInstance() {
return ( instance != null ) ? instance : ( instance = new Singleton() );
}

Appropriate way to pass instance of class to other classes (Java)

I have a main class which has a number of instance related methods that are often needed in other classes and I often find myself passing an instance of the main class in the constructor. I often find this goes several layers deep with classes having instances of the main class that has been copied from instance to instance which I can't imagine is good for memory usage.
Is there a way to do this without having to pass the instance in the constructor or a method or at least a way to reduce the memory that is used by the instances of the main class.
To make it clear I am not looking for static methods, it is designed to be able to have more than one instance of the main class.
Example code:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public void someMethod() {
//Do something
}
}
public class Class2 {
private final Main instance;
public Class2(Main instance) {
this.instance = instance;
Class3 class3 = new Class3(instance);
}
}
public class Class3 {
private final Main instance;
public Class3(Main instance) {
this.instance = instance;
instance.someMethod();
}
}
You can use Dependency Injection Design Pattern.
Dependency-Injection-Design-Pattern
Spring, Google Guice and Java EE CDI frameworks facilitate the
process of dependency injection through use of Java Reflection API and
java annotations. All we need is to annotate the field, constructor or
setter method and configure them in configuration xml files or
classes.
You could also use dependency injection to pass on the dependent attributes or objects to required classes.
One such popular framework is Google Guice.
You could make methods like someMethod() in the Main class static, or if that's not possible, make the Main class itself a singleton.
Example of the former approach:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public static void someMethod() {
//Do something
}
}
Now you don't have to pass an instance of Main around any more, because other classes can just call Main.someMethod() directly.

Why is it mandatory to have private Constructor inside a Singleton class

This is my singleton class for obtaining the database connection.
I have a question here: why it compulsory to have a private constructor inside a singleton class (as throughout my entire application I am calling this class only once) and as one instance of a class can be achieved using the static method?
Can this private constructor can be avoided, or is it mantadatory?
public class ConnPoolFactory {
private static DataSource dataSource;
private static Connection connection;
private ConnPoolFactory() {
System.out.println(" ConnPoolFactory cons is called ");
}
public static synchronized Connection getConnection() throws SQLException {
try {
if (connection == null) {
Context initContext = new InitialContext();
Context envContext = (Context) initContext
.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/Naresh");
connection = dataSource.getConnection();
} else {
return connection;
}
} catch (NamingException e) {
e.printStackTrace();
}
return connection;
}
}
Otherwise everyone can create an instance of your class, so it's not a singleton any more. For a singleton by definition there can exist only one instance.
If there no such a private constructor, Java will provide a default public one for you. Then you are able to call this constructor multiple times to create several instances. Then it is not a singleton class any more.
If you don't need lazy initiation:
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}
is the best way, because is thread safe.
The Singleton pattern typically includes a non-public constructor, for two reasons. A constructor has to exist because if there's no constructor at all, a public default constructor is included. If you have a public constructor, though, people can just make their own singletons at will (which someone inevitably will, meaning there can be more than one).
It doesn't have to be private, though. In fact, as i heard it, the Singleton pattern as specified by the GoF mentions a protected constructor, for some odd reason. Something about inheritance, i hear, but singletons and inheritance do not play well together at all anyway.
It's even possible to have a public constructor, as long as it can detect whether an instance already exists and throw an exception or something if it does. That'd be enough to guarantee singleness. But it's rather uncommon, because doing it that way complicates things by providing two apparent ways to acquire an instance -- only one of which will actually work. If you don't want outside code to be able to create a second instance, why should a constructor be part of the public interface?
For the singleton pattern you use an private constructor to ensure that no other instances can be created, otherwise it wouldn't be a singleton.
A static class is different from a singleton in that a a singleton class enforces that there is always at most one instance. A static class has no instances, and is just a bundle of static functions and static data.
So for a Singleton class, i.e. one with at most one instance, then a private constructor is required.
In your example, it looks like the Singleton class fits more than the static class- because of the connection and dataSource members. Make those members private, your constructor private and provide static methods that reference a static ConnPoolFactory instance. If instance is null, create a new one, otherwise just use it.
For singletons and utilty classes you can use an enum which is a final class and implicitly defines a private constructor.
enum Singleton {
INSTANCE
}
or
enum Utility {;
}
In your example above you have a utility class because you have no instance fields, methods and don't create an instance.
The comment as you said that If I am complete owner of my application and I will never commit mistake of creating instance of singleton class directly using the public constructor but will use the static method for getting it. But in real world, often application switch hands between multiple developers. If the new developer is not aware that you want only one instance of the class in the application, he/she may accidently create another one by using the public constructor.
It is mandatory. Your code may be fine, but others can use this code and instantiate another object, or you might do it by accident. This way is safe.
Singleton def:
Ensure the only one object need to create for the entire main stack (per main class).
If you want to satisfy above statement then we should give constructor as a private. Actually through singleton we are getting ref not object that's why it is not mandatory then we can create object in other classes but we can't access reference (Constructor as public).
Ex:
public class SingleTon {
private static SingleTon s;
public SingleTon() {}
public static SingleTon getInstance() {
if (s == null) {
s = new SingleTon();
System.out.println("ho ho");
} else{
return s;
}
return s;
}
}
Other class:
public class Demo {
public static void main(String[] args) {
//SingleTon s=SingleTon.getInstance();
SingleTon s11=new SingleTon();
SingleTon s12=new SingleTon();
s11.getInstance();
s12.getInstance();
}
}
Output:
ho ho

Singleton and unit testing

The Effective Java has the following statement on unit testing singletons
Making a class a singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.
Can anyone explain the why this is so ?
You could use reflection to reset your singleton object to prevent tests from affecting each other.
#Before
public void resetSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field instance = MySingleton.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, null);
}
Ref: unit-testing-singletons
The problem isn't testing singletons themselves; the book is saying that if a class you are trying to test depends on a singleton, then you will likely have problems.
Unless, that is, you (1) make the singleton implement an interface, and (2) inject the singleton to your class using that interface.
For example, singletons are typically instantiated directly like this:
public class MyClass
{
private MySingleton __s = MySingleton.getInstance() ;
...
}
MyClass may now be very difficult to automatedly test. For example, as #Boris Pavlović notes in his answer, if the singleton's behaviour is based on the system time, your tests are now also dependent on the system time, and you may not be able to test cases that, say, depend on the day of the week.
However, if your singleton "implements an interface that serves as its type" then you can still use a singleton implementation of that interface, so long as you pass it in:
public class SomeSingleton
implements SomeInterface
{
...
}
public class MyClass
{
private SomeInterface __s ;
public MyClass( SomeInterface s )
{
__s = s ;
}
...
}
...
MyClass m = new MyClass( SomeSingleton.getInstance() ) ;
From the perspective of testing MyClass you now don't care if SomeSingleton is singleton or not: you can also pass in any other implementation you want, including the singleton implementation, but most likely you'll use a mock of some sort which you control from your tests.
BTW, this is NOT the way to do it:
public class MyClass
{
private SomeInterface __s = SomeSingleton.getInstance() ;
public MyClass()
{
}
...
}
That still works out the same at run-time, but for testing you are now again dependent on SomeSingleton.
Mocks require interfaces, because what you're doing is replacing the real underlying behavior with an imposter that mimics what you need for the test. Since the client only deals with an interface reference type, it doesn't need to know what the implementation is.
You can't mock a concrete class without an interface, because you can't replace the behavior without the test client knowing about it. It's a completely new class in that case.
It's true for all classes, Singleton or not.
I think it actually depends on the implementation of the singleton access pattern.
For example
MySingleton.getInstance()
Might be very dificult to test while
MySingletonFactory mySingletonFactory = ...
mySingletonFactory.getInstance() //this returns a MySingleton instance or even a subclass
Doesn't provide any information about the fact that its using a singleton. So you can freely replace your factory.
NOTE: a singleton is defined by being only one instance of that class in an application, however the way it's obtained or stored doesn't have to be through static means.
It's oh so simple.
In unit-testing, you want to isolate your SUT (the class you're testing).
You don't want to test a bunch of classes, because that would defeat the purpose of unit-testing.
But not all classes do everything on their own, right? Most classes use other classes to do their work, and they kind of mediate between other classes, and add a bit of their own, to get the final result.
The point is - you don't care about how the classes your SUT depends on work. You care how your SUT works with those classes. That's why you stub or mock the classes your SUT needs. And you can use those mocks because you can pass them in as constructor parameters for your SUT.
With singletons - the bad thing is that the getInstance() method is globally accessible. That means that you usually call it from within a class, instead of depending on an interface you can later mock. That's why it's impossible to replace it when you want to test your SUT.
The solution is not to use the sneaky public static MySingleton getInstance() method, but to depend on an interface your class needs to work with. Do that, and you can pass in test doubles whenever you need to.
Singleton objects are created without any control from the outside. In one of the other chapters of the same book Bloch suggests using enums as default Singleton implementation. Let's see an example
public enum Day {
MON(2), TUE(3), WED(4), THU(5), FRI(6), SAT(7), SUN(1);
private final int index;
private Day(int index) {
this.index = index;
}
public boolean isToday() {
return index == new GregorianCalendar().get(Calendar.DAY_OF_WEEK);
}
}
Let's say we have a code that should be executed only on weekends:
public void leisure() {
if (Day.SAT.isToday() || Day.SUN.isToday()) {
haveSomeFun();
return;
}
doSomeWork();
}
Testing leisure method is going to be pretty hard. Its execution is going to be dependent on the day when it is executed. If it executes on a weekday doSomeWork() will be invoked and on weekends haveSomeFun().
For this case we would need to use some heavy tools like PowerMock to intercept the GregorianCalendar constructor, return a mock which will return an index corresponding to a weekday or weekend in two test cases testing both execution paths of the leisure method.
it’s impossible to substitute a mock implementation for a singleton
This is not true. You can subclass your singleton and setter inject a mock. Alternatively, you can use PowerMock to mock static methods. However the need to mock singletons can be symptomatic of poor design.
The real problem is Singletons when abused turn into dependency magnets. Since they are accessible everywhere, it can appear more convenient to put the functions you need in them rather than delegating to an appropriate class, especially for programmers new to OOP.
The testability problem is now you have a bunch of Singletons that are accessed by your object under test. Even though the object probably only uses a small fraction of methods in the Singletons, you still need to mock each Singleton and figure out which methods are depended on. Singletons with a static state (Monostate pattern) are even worse because you can have to figure out which interactions between objects are affected by the Singleton's state.
Used carefully, Singletons and testability can occur together. For instance, in absence of a DI framework, you can use Singletons as your Factories and ServiceLocators, which you can setter inject to create a fake service layer for your end-to-end tests.
It is possible, see the example
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class DriverSnapshotHandlerTest {
private static final String MOCKED_URL = "MockedURL";
private FormatterService formatter;
#SuppressWarnings("javadoc")
#Before
public void setUp() {
formatter = mock(FormatterService.class);
setMock(formatter);
when(formatter.formatTachoIcon()).thenReturn(MOCKED_URL);
}
/**
* Remove the mocked instance from the class. It is important, because other tests will be confused with the mocked instance.
* #throws Exception if the instance could not be accessible
*/
#After
public void resetSingleton() throws Exception {
Field instance = FormatterService.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, null);
}
/**
* Set a mock to the {#link FormatterService} instance
* Throws {#link RuntimeException} in case if reflection failed, see a {#link Field#set(Object, Object)} method description.
* #param mock the mock to be inserted to a class
*/
private void setMock(FormatterService mock) {
Field instance;
try {
instance = FormatterService.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(instance, mock);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Test method for {#link com.example.DriverSnapshotHandler#getImageURL()}.
*/
#Test
public void testFormatterServiceIsCalled() {
DriverSnapshotHandler handler = new DriverSnapshotHandler();
String url = handler.getImageURL();
verify(formatter, atLeastOnce()).formatTachoIcon();
assertEquals(MOCKED_URL, url);
}
}
Use PowerMock to mock Singleton class (SingletonClassHelper) instance and non-static method (nonStaticMethod) which is called in task.execute().
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#PrepareForTest({ SingletonClassHelper.class })
#RunWith(PowerMockRunner.class)
public class ClassToTest {
#InjectMocks
Task task;
private static final String TEST_PAYLOAD = "data";
private SingletonClassHelper singletonClassHelper;
#Before
public void setUp() {
PowerMockito.mockStatic(SingletonClassHelper.class);
singletonClassHelper = Mockito.mock(SingletonClassHelper.class);
when(SingletonClassHelper.getInstance()).thenReturn(singletonClassHelper);
}
#Test
public void test() {
when(singletonClassHelper.nonStaticMethod(parameterA, parameterB, ...)).thenReturn(TEST_PAYLOAD);
task.execute();
}
}
durian-globals does lazy double-locked initialization of singletons, but also has a simple test-only API which allows you to replace the implementation for unit testing.
As far as I know, a class implementing a Singleton cannot be extended (superclass constructor is always called implicitly and the constructor in a Singleton is private). If you want to mock a class you have to extend the class. As you see in this case it wouldn't be possible.
The problem with singletons (and also with static methods) is that it makes it hard to replace the actual code with a mocked implementation.
For example consider the following code
public class TestMe() {
public String foo(String data) {
boolean isFeatureFlag = MySingletonConfig.getInstance().getFeatureFlag();
if (isFeatureFlag)
// do somethine with data
else
// do something else with the data
return result;
}
}
It is not easy to write a unit test for the foo method and verifying the correct behavior is performed.
This is because you can't easily change the return value of getFeatureFlag.
The same problem exists for static methods - it's not easy to replace the actual target class method with a mock behavior.
Sure, there are workarounds like powermock, or dependency injection to the method, or reflection in tests.
But it is much better not to use singletons in the first place
Below there is the solution I had to adopt with some immutable Kotlin singleton to test them
Suppose you have a singleton class like this:
class MySingleton private constructor(
{your dependencies}
) {
companion object {
#JvmStatic
private var INSTANCE: MySingleton? = null
#JvmStatic
fun getInstance(): MySingleton {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: MySingleton(
{your dependencies}
).also {
INSTANCE = it
}
}
}
}
}
You can do this in your kotlin junit tests:
#After
fun after() {
val instance = MySingleton.Companion::class.memberProperties.find {
it.name == "INSTANCE"
}
instance!!.isAccessible = true
instance.javaField!!.set(null, null)
}
You just need to add the kotlin-reflect artifact to your dependencies

Categories