Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test Singleton class - C++?

What are the ways to unit test a Singleton pattern in C++? (with examples please)

like image 395
Aquarius_Girl Avatar asked Feb 08 '12 10:02

Aquarius_Girl


People also ask

Why singleton is hard to unit test?

It's very difficult to write unit tests for code that uses singletons because it is generally tightly coupled with the singleton instance, which makes it hard to control the creation of singleton or mock it.

How do you know if a class is a singleton C#?

So, simply call the method which is returning your expected singleton type of object and call hashcode() method on it. If it prints the same hashcode each time, it means it's singleton, else it's not.

What is singleton class in C?

Singleton in C++ Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.

What is unit testing C?

A Unit Testing Framework for C CUnit is a lightweight system for writing, administering, and running unit tests in C. It provides C programmers a basic testing functionality with a flexible variety of user interfaces. CUnit is built as a static library which is linked with the user's testing code.


1 Answers

Make the implementation of the singleton a separate class, and make a wrapper that implements the "singletonness" outside. That way you can test the implementation as much as you like (except the singleton behavior which is trivial and unnecessary.

class SingletonImpl {
public:
  int doit(double,double);
};

class Singleton {
public:
  Singleton& instance() {...}
  int doit(double a,double b) {impl->doit(a,b);}
  ...
private:
  SingletonImpl impl;
}
like image 170
daramarak Avatar answered Oct 06 '22 05:10

daramarak