Should Unit Tests Be Written for Classes Calling Other Classes?

mockingunit testing

Suppose that there are two class 'A' and 'B'

'A' has a lot of nested conditions that have all unit test covered.

'B' has a property that will call class 'A' and return value according to the result of class 'A'

On class 'B', when i want to write unit test. Should i just mock class A and verify on class B that it has been called a specific class 'A' method.

Best Answer

In general, yes. The point of a unit test for B is to demonstrate that method B.b() does its job given the appropriate collaborators. If there were a problem within A, it should already be discovered by the unit test for A, so duplicating this check in the test for B is wasted effort. Just go ahead and supply a MockA that you can query to demonstrate that A.a() was, in fact, called.

In practice, for small classes and methods it can become more effort to supply mocks for every collaborator than just to go ahead and test the result of B.b() for correctness. Strictly speaking, this is no longer a unit test because it depends on other classes, but since the major point of keeping tests small and focused is to save development effort without compromising correctness, I don't see why you shouldn't use the already-verified functionality of A to write a smaller, neater test for B.