PowerMock - Mock a Singleton with a Private Constructor - java

I'm using PowerMock with EasyMock, and wondered how I might mock a singleton with a private constructor?
Let's say I have the following class:
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return singleton;
}
public int crazyServerStuff() { ... }
}
And a class which uses this:
public class Thing {
public Thing() {}
public int doStuff(Singleton s) {
return s.crazyServerStuff() + 42;
}
}
How might I mock the crazyServerStuff method?
I've tried the following:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Singleton.class)
public class ThingTest extends AndroidTestCase {
#Test
public void testDoStuff() {
MemberModifier.suppress(MemberModifier.constructor(Singleton.class));
Singleton mockSingleton = PowerMock.createMock(Singleton.class);
...
}
}
But I get the error java.lang.IllegalArgumentException: No visible constructors in class Singleton
Does anyone know what I'm missing?

I don't think you should suppress the constructor, but rather mock it:
PowerMock.expectNew(Singleton.class).andReturn(mockObject)
https://code.google.com/p/powermock/wiki/MockConstructor

Sadly I don't think this is possible for Android - see this answer.
If you're not on Android, it looks like this is how you do it.

Related

Using #Autowired services in static method

I am trying to autowire multiple services (around 10-15) in a class having static methods and came across a solution mentioned in this post about using #Autowired constructor. Can we use constructor #Autowired approach for multiple classes as well?
For example, suppose I have two classes Foo1 and Foo2. Can I use the single constructor for both classes like
#Component
public class Boo {
private static Foo1 foo1;
private static Foo2 foo2;
#Autowired
public Boo(Foo1 foo1, Foo2 foo2) {
Boo.foo1 = foo1;
Boo.foo2 = foo2;
}
public static void randomMethod() {
foo1.doStuff();
foo2.doSomeOtherStuff();
}
}
Or is there any other way to achieve this ?
Spring + static is a very bad idea.
I suggest making the randomMethod() not static and then inject Boo everywhere you earlier had to call the static method. E.g change this:
class A {
public void run() {
Boo.randomMethod();
}
}
To this:
#Component
public class A {
private final Boo boo;
#Autowired
public A(Boo boo) {
this.boo = boo;
}
public void run() {
boo.randomMethod();
}
}
This construct is the spring intended way, and I suggest you to use it.

how to mock private static inner class?

I have a class like
public class Enclosing {
public String methodA() {
Inner.getContext();
......
}
private static class Inner{
// some context init
public static Context getContext() {
.....
}
}
}
Now I want to test methodA without invoking the real Inner.getContext(). I have been searching all over but cannot find a working solution. I am using Java 8. Can I have some help please? Many thanks
You can apply the extend and override technique, here's how it works.
Given this code:
public class Enclosing {
public String methodA() {
Inner.getContext();
......
}
You can move the Inner.getContext() call to a protected method:
public class Enclosing {
public String methodA() {
getContext();
......
}
protected void getContext() {
Inner.getContext();
......
}
And then in your test case, you can extend the enclosing class, and override the protected method to do whatever you want with it:
#Test
public void test_something() {
Enclosing enclosing = new Enclosing() {
#Override
protected void getContext() {
// do what you need here
}
};
// your test code on enclosing where you control getContext
}
As an alternative to #janos' answer, you can inject a strategy (basically, the "prefer composition over inheritance" approach):
interface ContextStrategy {
void getContext();
}
and then inject an instance of this into the constructor of Enclosing:
class Enclosing {
private final ContextStrategy ctxStrategy;
Enclosing(ContextStrategy ctxStrategy) {
this.ctxStrategy = ctxStrategy;
}
String methodA() {
ctxStrategy.getContext();
// ...
}
}
and then implement this interface for the production case, as a nested class in Enclosing:
static class ContextStrategyImpl implements ContextStrategy {
#Override public void getContext() {
Inner.getContext();
}
}
and implement an alternative version for your mock case.
You should not mock a private class (whether it is a nested class like the one here or an actual inner class).
Instead, mock only the Context type if it's really needed (otherwise, use a real Context object). For example, such a test is shown below, using the JMockit library:
#Test
public void mockingTheContext(#Mocked Context anyContext) {
new Expectations() {{
// record any method call results expected from "anyContext"
}};
new Enclosing().methodA();
new Verifications() {{
// verify calls to "anyContext", if applicable
}};
}
In the test above, the fact that Context is created inside a nested class is irrelevant. In general, mocking private methods or classes should always be avoided, since they are only implementation details.

Java singleton enum programmed to the interface?

This is my first post on here so I will try to be precise. This is for a university project, we have to create a fish tank simulation on top of an OO architecture that we individually make. I'm exploring the uses of singletons and have found them quite useful, however reading online the way I currently implement it is not thread safe.
The way I currently implement it (Think its the lazy method) Note: We have to go through the interface
public interface myInterface
{
void foo();
}
public class myClass implements myInterface
{
private static myInterface instance;
private myClass(){}
private static myInterface Instance()
{
if(instance == null)
instance = new myClass();
return instance;
}
public void foo()
{
//Do stuff
}
public void bar()
{
//Do More Stuff
}
}
This works well however its not thread safe I could add the synchronized keyword to the getter but I've read that that is quite heavy on the system and I have quite a few singletons.
private synchronized static myInterface Instance()
{
if(instance == null)
instance = new myClass();
return instance;
}
I have then moved on to an enum singleton which is thread safe and is not heavy on the system however I am unsure on how to program it to the interface.
public enum myClass implements myInterface
{
INSTANCE;
private myClass(){}
public void foo()
{
//Do stuff
}
public void bar()
{
//Do More Stuff
}
}
In programming to the interface I mean when I call the singleton I can only access methods that are in the interface (please correct me if I'm referring to this wrongly). This is where the way I have done the enum singleton fails. For example: With the lazy singleton I can not call this as its not in the interface:
myClass.Instance().bar();
But it can call this which is correct, as it is in the interface.
myClass.Instance().foo();
With the enum however I can call this and its not programming to the interface
myClass.INSTANCE.bar();
I understand why its doing this as the class is an enum so it will be able to call everything in that enum class. So after this long post which I apologise for, the main question is: Can I make the enum version only call methods that are declared in the interface?
If it can't how heavy is a synchronized method on the system, I would have around 4-6 of them?
Please Note: Even though this is for a university project we are only running the simulation on one thread so it does not even need to be thread safe. I don't quite understand multi-threading but I thought it would be a good learning opportunity.
You can always hide your enum implementation as well if you prefer the enum route:
public interface Singleton {
void foo();
}
public final class SingletonAccessor {
public static Singleton getInstance() {
return SingletonImpl.INSTANCE;
}
private SingletonAccessor() {
}
private enum SingletonImpl implements Singleton {
INSTANCE;
public void foo() {
// ...
}
public void bar() {
// ...
}
}
}
EDIT
As pointed out by Peter Lawrey in the comments, you can even use an enum for the SingletonAccessor :)
public enum SingletonAccessor {
SINGLETON;
public Singleton get() {
return SingletonImpl.INSTANCE;
}
private enum SingletonImpl implements Singleton {
INSTANCE;
public void foo() {
// ...
}
public void bar() {
// ...
}
}
}
You can cast it to the interface or
myInterface my = myClass.INSTANCE;
my.foo();
You can still use a method like
myClass.getInstance().foo();
But this isn't a real solution IMHO.
Can I make the enum version only call methods that are declared in the interface?
Ultimately you have to decide which methods you want on the instance which are public. If you make a method or field public, you can access it and if you don't want to be able to access it, make it private.
At some point you have to trust you know what you are doing and you do things for a reason. You don't have to think up ways to prevent yourself from call code you wrote.
just simply change your singleton class this way:
public class myClass implements myInterface
{
private static myInterface instance = new myClass();
private myClass(){}
private static myInterface Instance()
{
return instance;
}
public void foo()
{
//Do stuff
}
public void bar()
{
//Do More Stuff
}
}
this will assure that the singleton object will be created at class-loading time, and you don't need to worry about race-conditions in the Instance() method
Try looking at java.util.concurrent.atomic.AtomicReference. Specifically compareAndSet.
instance.compareAndSet(null, new MyClass());
That is if your instance field is null, set to new object, if not null, leave intact. Should be less heavy.

Avoid Object Creation in Java

How to stop other classes to create the object of the class using new operator in java. For Example, i have one class A. i don't want any other class to create its object using new operator.
One Approach is that i can throw IllegalArgumentException in the constructor of class A.
is there any other?
public class A{
public A(){
throw IllegalArguementException();
}
}
The approach what you followed is wrong.. you can't create object of your class as well with this approach.
So you must make your construction private and write static method to get the instance of the class.
class Test
{
private Test(){ }
public static Test getTestInstance(){
return new Test();
}
}
Hope it helps,
You can do it by making the constructor private.
class A
{
int i;
private A()
{
i=1;
}
public static A getInstance()
{
return new A();
}
}
class B
{
A a;
public B()
{
/* a=new A(); //This doesn't compile */
}
}
Implementing Singleton in Java 5 or above version using Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.
public enum SingletonEnum {
INSTANCE;
public void doYourStuff(){
System.out.println("Singleton using Enum");
}
}
And this can be called from clients :
public static void main(String[] args) {
SingletonEnum.INSTANCE.doYourStuff();
}
You can make the class abstract (though in this case no instance of this class can be instantiated by any class, so perhaps it's not what you want), or make the constructor private.
private A() {}
Make the constructor private.

How to construct a Non Instantiable AND Non Inheritable Class in Java

The question says it all.
I know the Singleton pattern (with final to its class) is a solution. Are there any other possible ways we can achieve this?
Abstracting a class makes it non-instantiable. Making it final makes it non-inheritable.
How do we combine both?
public final 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;
}
Code Ref: http://www.javacoffeebreak.com/articles/designpatterns/index.html
Make the constructor private:
public final class Useless {
private Useless() {}
}
A private constructor is the normal object-oriented solution. However, it would still be possible to instantiate such a class using reflection, like this:
Constructor<Useless> con = Useless.class.getDeclaredConstructor();
con.setAccessible(true); // bypass "private"
Useless object = con.newInstance();
To prevent even reflection from working, throw an exception from the constructor:
public final class Useless {
private Useless() {
throw new UnsupportedOperationException();
}
}
You mean a class with static methods only? Class cannot be both final and abstract. But you can use private constructor to make it not instantinable.
final class StaticOnly {
private StaticOnly() {
throw new RuntimeException("Do not try to instantiate this");
}
public static String getSomething() {
return "something";
}
}
Below example will work to. You won't instantiate it because it's abstract. You won't inherit it because there is no way to call super constructor from external subclass (only inner subclass will work)
abstract class StaticOnly {
private StaticOnly() {}
public static String getSomething() {
return "something";
}
}
enum will work too
enum StaticOnly {
S;
public static String getSomething() {
return "something";
}
}
but it always have at least one instance (here it's S).
I would use the simplest Singleton pattern
enum Singleton {
INSTANCE;
}
The enum type is non-instance-able and non-inheritable and the classes initialisation is lazy and thread safe.
To declare there should never be an instance you can also use an enum
enum Utilities {
; // no instances
// add static methods here
}

Categories