Different Singleton instances with JUnit tests - junit

I have a standalone singleton which successfully passes the test. But with a group of tests this fails since once a singleton is defined it does not allow to reset the instance.
Any ideas about how to go about this?

I assume you have a private static field within your singleton class to store the initialized instance.
If you do not want to modify your code, you can define a teardown method which run after every test, and in this method you set this static field to null via reflection as seen here.

Don't use a singleton.
Specifically, the only difference between a singleton and a global variable is that the singleton tries to enforce a single instance (by making the constructor private, for example).
Instead, make the constructor public and write tests using new instances. In your actual program, use getInstance() to get the canonical global instance (or use an IOC container).
And remember that singletons are pathological liars.
If you're still too comfortable with the idea of a Singleton, instead of making the constructor public you can add a public (and static) factory method to create instances in a way that can't be used by accident, e.g.:
public static MyClass TEST_CreateInstance() {
return new MyClass();
}

Spring provides the DirtiesContext annotation for this particular use case where you need new instances of the singleton beans for each testcase. It basically creates a new application context for each testcase/testclass which has this annotation applied.

You can add a method to destroy the singleton, for example destroyMe(); where you deinitialize everything and set the instance of the singleton to null.
public void destroyMe(){
this.instance = null;
//-- other stuff to turn it off.
}
I will leave synchronization problems though ;)
But why do you need to re-initialize your singleton for each test? It should not differ based on the concept of the singleton.

I highly recommend moving away from Singletons as a design pattern, and using Singleton as a scope (Dependency Injection). This would simply make your problem go away.
But assuming you are stuck in the world of Singletons, then you have a few options depending on if you are testing the Singleton or the dependency.
If you are testing the dependant item then you can mock the Singleton using PowerMock and JMockIt. See my previous post about mocking Runtime.getRuntime for instructions on how to go about this.
If you are testing the Singleton then you need to relax the rules on construction, or give the Singleton a "Reset" method.

generally beware of singletons, most often they are evil, bad design and tend to represent big yucky global variables (which is bad for maintenance).
still to get tests in place first you can do:
static setInstance(...){ //package visibility or in difficult cases you have to use public
instance = ...;
}
as said this is more a workaround. so get first tests place, but then refactor away from singleton pattern.

Singleton instance needs to be passed to SUT by test itself - that way you create singleton (and destroy) for each test. Adopting IoC and mocking framework, like Mockito, would render this approach almost trivial.

Very late to the party here, but for anyone looking for an answer, in case you don't want / cannot modify the code.
#BeforeEach
public void setup() {
object = Singleton.getInstance();
}
#AfterEach
public void after() {
// cleaning the singleton instance
ReflectionTestUtils.setField(object , "internal_object_name", null);
}
your Singleton class should be something like this:
public final class Singleton {
private static Singleton internal_object_name;
private Singleton (){}
public static Singleton getInstance() {
if (object == null)
return new Singleton();
else
return internal_object_name;
}

Related

Is there a way to share #Before code between tests suite classes?

I am testing a Cordova plugin in Java/Android and I need to initialize my Plugin class and set some state before I run my Tests.
#Before
public void beforeEach() throws Exception {
System.out.println("Creating new Instance ");
PowerMockito.mockStatic(Helpers.class);
PowerMockito.when(Helpers.canUseStorage(any(), any())).thenReturn(true);
MyLogger myLoggerMock = PowerMockito.mock(MyLogger.class);
PowerMockito.doNothing().when(myLoggerMock, "log", anyString());
PowerMockito.whenNew(MyLogger.class).withAnyArguments().thenReturn(myLoggerMock);
this.sut = spy(new FilePicker());
PowerMockito.doNothing().when(this.sut).pick(any(), any());
}
I want to create a Test Suite / Java Class per public function, but I do not want to repeat that code every time.
Is there a way to share that before each between test suites? I have found ClassRule but I think I do not do what I need (or I am understanding it wrong... I am really new in Java)
In Typescript we can share beforeEachfunctions with several suites, and each suite can have their own beforeEach
One possible ways is using inheritance:
Make all test classes extend from one "parent test" class and define a #Before in a parent class.
So it will be called automatically for all the subclasses:
public class ParentTest {
#Before
public void doInitialization() {
....
}
}
public class Test1Class extends ParentClass {
#Test
public void fooTest() {
// doInitialization will be executed before this method
}
#Test
public void barTest() {
// doInitialization will be executed before this method as well
}
}
Two notes:
Note 1
In the code you use sut (subject under test) - this obviously should not be in the parent's doInitialization method, so its possible that Test1Class will also have methods annotated with #Before (read here for information about ordering and so forth)
Then the `sut gets initialized with Spy which is frankly weird IMHO, the Subject Under Test should be a real class that you wrote, but that's beyond the scope of the question, just mentioning it because it can point on mistake.
Note 2
I'm writing it in an an attempt to help because you've said that you're new in Java, this is not strictly related to your question...
While this approach works in general you should be really cautious with PowerMockito. I'm not a PowerMockito expert and try to avoid this type of mocks in my code but in a nutshell the way it manipulates the byte code can clash with other tools. From your code: you can refactor the HelperUtils to be non-static and thus avoid PowerMocking in favor of regular mocking which is faster and much more safe.
As for the Logging - usually you can compromise on it in unit test, if you're using slf4j library you can config it to use "no-op" log for tests, like sending all the logging messages into "nothing", and not-seeing them in the console.

What is the scope of the #SuppressStaticInitializationFor PowerMock annotation?

Does anyone know what is the scope of this annotation? For example, if I have multiple JUnit test classes that run sequentially in the same VM, and the first test uses #SuppressStaticInitializationFor, does that suppress the static initialization for all the subsequent test classes, too? I ask because I am under the impression that static state persists for the life of the JVM.
The scope is per classloader. Once you've used #SuppressStaticInitializationFor it'll affect the class in all other tests. You can however #SuppressStaticInitializationFor at the method level instead and that way it won't affect other tests.
you can use #SuppressStaticInitializationFor annotation at the class-level or at the method-level of the test where you want it to be suppressed.
#RunWith(PowerMockRunner.class)
#SuppressStaticInitializationFor("com.main.java.CassName")
public class TestClassName extends PowerMockTestCase {
//code
#SuppressStaticInitializationFor("com.main.java.AnotherClassName")
public void testMethod() {
//code
}
}
This way you can control which method should suppress static initializers(constructors) and for which class.

What do you call a "singleton" that allows a public constructor for additional instances?

I'm making a class that supports the Singleton use (one instance is available), yet it also supports normal instance use (via a public constructor).
If you only want one, use that one. If you want 5, new them up.
I clearly can't call this singleton, or some other dev will come along and make my constructor non-public. What can I call this to indicate how it is to be used? Naming is hard.
Some guesses for your amusement:
"StaticallyAvailable"?
"ThreadReady"?
"SingletonOptional"?
It sounds like you've got a "default instance". You could name your object along those lines.
Usually the point of a singleton is for an object that has an unique instance. If multiple copies of the class can exist, then it means that "oneness" is not a necessary behavior. This is just like any other object.
Probably, the reason why you code it as a Singleton is for the global access. Just call it a global object then.
A Pool ?
(esp if you know how about the instance count early, but want to encapsulate some of the behaviour of constructing / destroying)
This does not sound like a singleton to me, it sounds like a regular class that always has at least one instance. Calling this a singleton, and writing the code as though it was one (eg. private static MySingleton instance = new MySingleton();) is confusing - decouple the "always present" instance from your class definition somehow. Make it clear in your implementation that this is a normal class that just happens to always have at least 1 instance around.
You could create a default instance getter.
private TheClass defaultInstance;
public Default{ get{ return defaultInstance??(defaultInstance = new TheClass());}

How do you create your Factories?

So, coming upon the subject of Factories, I'm wondering how they are set up.
From where I stand, I can see 3 types of Factories:
All In One
A factory that basically contains all of the classes used in an application. It feels like it is just having a factory for the sake of having a factory, and doesn't really feel structured.
Example (Where ClassA, Class B, and ClassC have nothing in common except being in the same App):
class Factory
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
Code samples provided are in PHP. However, this question is language-agnostic.
Built-In Factory
The next one is mixing in static functions with the regular functions in order to make special creation patterns (see this question)
Example:
class ClassA
{
public static function buildClass()
public function __construct()
}
Factory On-the-Side
The last one I can think of is having a factory for individual classes, or individual sets of classes. This just seems to variable to be used in an uniform manner.
Example (Where ClassA, B, and C are related, and 1, 2, and 3 are related):
class FactoryAlpha
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
class FactoryNumeric
{
public static function buildClass1()
public static function buildClass2()
public static function buildClass3()
}
My question is: Are all of these bad ideas, are any of them bad ideas? Are there other ways of creating factories? Are any of these actually good ideas? What is a good/best way to create Factories.
The point of a factory seems to be to have the code that uses it not need to know which concrete class will be constructed (this should be handled by configuring the factory). That seems to rule out "All-in One" and "Factory-on-the-Side".
I like the approach that Java libraries often use: You have a static method that creates the Factory. The Factory has a getInstance method that creates the instance. This gives you two points of configuration (via system properties): The default FactoryImpl has a number of settings, such as the class it should produce, and if these configuration options are not enough, you can also swap out the FactoryImpl altogether.
As for "All-in One" vs "Factory-on-the-Side", a Factory should not produce unrelated classes I think. Again, it Java terms, every factory produces instances of a certain interface.
"All-in-One" sounds like something that should be replaced with Dependency Injection (where you have a container that produces all kinds of instances and injects them into the application).
If you are really interested in "Preferred technologies", I'd replace them all with Dependency Injection.
If that seems to heavy, just remember that you may not be seeing every use for your factory so don't "New" a hard-coded class in your factory. Instead, have a "Setter" that can specify what class needs to be injected.
This will come in handy later when you are unit testing and need to start injecting mock classes.
But as you make this more general, abstract and reusable, you'll end up back at DI. (Just don't say I didn't warn you)
There's really just two standard sorts of factories, at least according to GOF and the slew of patterns books that followed: The basic Factory, and the Abstract Factory.
A Factory generally returns a concrete instance that the caller refers to through an interface, like so:
// createWidget() here instantiates a BigWidget or SmallWidget or whatever the context calls for
IWidget widget = WidgetFactory.createWidget(someContextValue);
Using a factory with an interface in this way keeps the caller from being coupled into a specific type of the returned object. Following the venerable Single Responsibility Principle, a factory should do one thing, that is, return a concrete instance of the interface that was called for, and nothing more. A basic factory should only have the job of creating one type of object.
An Abstract Factory, on the other hand, can be thought of as a factory of factories, and might be closer to what you were thinking of as an "all in one" factory. An Abstract Factory is usually configured at start-up to return a group of related factories, for instance factories that might create a particular family of GUIs depending on a given context. This is an example of Dependency Inversion that has largely been replaced by using IOC containers like Spring.

Fluent Interfaces - Method Chaining

Method chaining is the only way I know to build fluent interfaces.
Here's an example in C#:
John john = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
Assert.IsNotNull(john);
[Test]
public void Should_Assign_Due_Date_With_7DayTermsVia_Invoice_Builder()
{
DateTime now = DateTime.Now;
IInvoice invoice = new InvoiceBuilder()
.IssuedOn(now)
.WithInvoiceNumber(40)
.WithPaymentTerms(PaymentTerms.SevenDays)
.Generate();
Assert.IsTrue(invoice.DateDue == now.AddDays(7));
}
So how do others create fluent interfaces. How do you create it? What language/platform/technology is needed?
The core idea behind building a fluent interface is one of readability - someone reading the code should be able to understand what is being achieved without having to dig into the implementation to clarify details.
In modern OO languages such as C#, VB.NET and Java, method chaining is one way that this is achieved, but it's not the only technique - two others are factory classes and named parameters.
Note also that these techniques are not mutually exclusive - the goal is to maximize readabilty of the code, not purity of approach.
Method Chaining
The key insight behind method chaining is to never have a method that returns void, but to always return some object, or more often, some interface, that allows for further calls to be made.
You don't need to necessarily return the same object on which the method was called - that is, you don't always need to "return this;".
One useful design technique is to create an inner class - I always suffix these with "Expression" - that exposes the fluent API, allowing for configuration of another class.
This has two advantages - it keeps the fluent API in one place, isolated from the main functionality of the class, and (because it's an inner class) it can tinker with the innards of the main class in ways that other classes cannot.
You may want to use a series of interfaces, to control which methods are available to the developer at a given point in time.
Factory Classes
Sometimes you want to build up a series of related objects - examples include the NHibernate Criteria API, Rhino.Mocks expectation constraints and NUnit 2.4's new syntax.
In both of these cases, you have the actual objects you are storing, but to make them easier to create there are factory classes providing static methods to manufacture the instances you require.
For example, in NUnit 2.4 you can write:
Assert.That( result, Is.EqualTo(4));
The "Is" class is a static class full of factory methods that create constraints for evaluation by NUnit.
In fact, to allow for rounding errors and other imprecision of floating point numbers, you can specify a precision for the test:
Assert.That( result, Is.EqualTo(4.0).Within(0.01));
(Advance apologies - my syntax may be off.)
Named Parameters
In languages that support them (including Smalltalk, and C# 4.0) named parameters provide a way to include additional "syntax" in a method call, improving readability.
Consider a hypothetical Save() method that takes a file name, and permissions to apply to the file after saving:
myDocument.Save("sampleFile.txt", FilePermissions.ReadOnly);
with named parameters, this method could look like this:
myDocument.Save(file:"SampleFile.txt", permissions:FilePermissions.ReadOnly);
or, more fluently:
myDocument.Save(toFile:"SampleFile.txt", withPermissions:FilePermissions.ReadOnly);
You can create a fluent interface in any version of .NET or any other language that is Object Oriented. All you need to do is create an object whose methods always return the object itself.
For example in C#:
public class JohnBuilder
{
public JohnBuilder AddSmartCode(string s)
{
// do something
return this;
}
public JohnBuilder WithfluentInterface(string s)
{
// do something
return this;
}
public JohnBuilder ButHow(string s)
{
// do something
return this;
}
}
Usage:
John = new JohnBuilder()
.AddSmartCode("c#")
.WithfluentInterface("Please")
.ButHow("Dunno");
AFAIK, the term fluent interface does not specify a specific technology or framework, but rather a design pattern. Wikipedia does have an extensive example of fluent interfaces in C♯.
In a simple setter method, you do not return void but this. That way, you can chain all of the statements on that object which behave like that. Here is a quick example based on your original question:
public class JohnBuilder
{
private IList<string> languages = new List<string>();
private IList<string> fluentInterfaces = new List<string>();
private string butHow = string.Empty;
public JohnBuilder AddSmartCode(string language)
{
this.languages.Add(language);
return this;
}
public JohnBuilder WithFluentInterface(string fluentInterface)
{
this.fluentInterfaces.Add(fluentInterface);
return this;
}
public JohnBuilder ButHow(string butHow)
{
this.butHow = butHow;
return this;
}
}
public static class MyProgram
{
public static void Main(string[] args)
{
JohnBuilder johnBuilder = new JohnBuilder().AddSmartCode("c#").WithFluentInterface("Please").ButHow("Dunno");
}
}
Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing a series of blog posts about techinics of designing a fluent interface.
Check it out at:
Guidelines to Fluent Interface design in C# part 1
I have a section there about Chaining X Nesting that can be interesting to you.
In the following posts I will talk about it in a deeper way.
Best regards,
André Vianna
Fluent interface is achieved in object oriented programming by always returning from your methods the same interface that contains the method. Consequently you can achieve this effect in java, javascript and your other favorite object oriented languages, regardless of version.
I have found this technique easiest to accomplish through the use of interfaces:
public interface IFoo
{
IFoo SetBar(string s);
IFoo DoStuff();
IFoo SetColor(Color c);
}
In this way, any concrete class that implements the interface, gets the fluent method chaining capabilities. FWIW.. I wrote the above code in C# 1.1
You will find this technique littered throughout the jQuery API
A couple of things come to mind that are possible in .Net 3.5/C# 3.0:
If an object doesn't implement a fluent interface, you could use Extension Methods to chain your calls.
You might be able to use the object initialization to simulate fluent, but this only works at instantiation time and would only work for single argument methods (where the property is only a setter). This seems hackish to me, but the there it is.
Personally, I don't see anything wrong with using function chaining if you are implementing a builder object. If the builder object has chaining methods, it keeps the object you are creating clean. Just a thought.
This is how I've built my so called fluent interfaces or my only forary into it
Tokenizer<Bid> tkn = new Tokenizer<Bid>();
tkn.Add(Token.LambdaToken<Bid>("<YourFullName>", b => Util.CurrentUser.FullName))
.Add(Token.LambdaToken<Bid>("<WalkthroughDate>",
b => b.WalkThroughDate.ToShortDateString()))
.Add(Token.LambdaToken<Bid>("<ContactFullName>", b => b.Contact.FullName))
.Cache("Bid")
.SetPattern(#"<\w+>");
My example required .net 3.5 but that's only cause of my lambda's. As Brad pointed out you can do this in any version of .net. Although I think lambda's make for more interesting possibilities such as this.
======
Some other good examples are nHibernate's Criteria API, there is also a fluent nhibernate extension for configuring nhibernate but I've never used it
Dynamic keyword in C# 4.0 will make it possible to write dynamic style builders. Take a look at following article about JSON object construction.