Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a Singleton class?

I am using RSpec and want to test the constructor of a Singleton class more than one time.

How can I do this?

Best regards

like image 891
brainfck Avatar asked Dec 15 '09 17:12

brainfck


People also ask

What is singleton testing?

The Singleton pattern is a useful pattern in Android development, and Java development at large. The Singleton pattern is defined as follows: In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

How do you write a unit test case for a singleton class in Java?

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() ; ... }

Can we write unit test for singleton class?

Singleton classes do not allow for Test Driven Development (TDD) The laws of TDD. Unit testing depends on tests being independent of one another, so the tests can be run in any order and the program can be set to a known state before the execution of every unit test.

Why is singleton testing hard?

It's hard to test code that uses singletons.You can't control the creation of the singleton object because often it is created in a static initializer or static method. As a result, you also can't mock out the behavior of that Singleton instance.


1 Answers

Singleton classes essentially do this

def self.instance
  @instance ||= new
end

private_class_method :new

So you can bypass the memoization altogether by calling the private method new using send

let(:instance) { GlobalClass.send(:new) }

A nice benefit of this way is that no global state is modified as a result of your tests running.


Probably a better way, from this answer:

let(:instance) { Class.new(GlobalClass).instance }

This creates an anonymous class which inherits from GlobalClass, which all class-level instance variables are stored in. This is then thrown away after each test, leaving GlobalClass untouched.

like image 200
Cameron Martin Avatar answered Sep 24 '22 18:09

Cameron Martin