I’ve a code like following:
class B;
class A
{
A()
{
}
bool MethodA()
{
B *pB = new B();
bool bRet = pB->SomeFunction();
// remaining logic;
return bRet;
}
~A(){}
};
I need to write tests for MethodA. So I think I need to break the dependency on class B. What is the best way to do it? If it was a member variable, I could have injected a stub via constructor. Is there any solution that doesn’t involve change in production code?
If a change is necessary, what’s the best way?
I use NUnit and is working on some unmanaged code here. Please help!
edit: There is another headache that I missed! class B is a C++ class which I shouldn’t change its implementation. class A is in C++/CLI, which acts as wrapper to B. So I think that inhibits the probability of an Interface for B as I cannot touch B.
No. There is no solution that doesn’t include changing that design, mostly because that design is bad. A and its dependency B are tightly coupled, which makes as bad as it gets in terms of object-oriented programming: you need to invert the control of dependencies. Testing is only one reason why that design is bad, but it’s not the only one. Portability, flexibility, separation of concerns, are other.
The best way (the only good way) to make it testable, and to make it better, is dependency injection.
You need to inject B into A, using either a constructor (that takes an interface to B as a parameter) or a setter. And whoever controls A (and does a
new A()) should pass the dependency B to it (new A(new B()), orA.setB(new B())).Once that is done, unit-testing the method will become very easy.