What are the ways to unit test a Singleton pattern in C++? (with examples please)
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With