2

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.

2 Answers 2

7

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.

1

In general, it depends.

Specifically, I would say it depends on whether the dependended-on class A is encapsulated or injected.

In the first case, you are testing 'does B work?' In the second, it is more 'can B work, given a suitable A?'.

Getting this distinction wrong, in either direction, is a fairly common cause of bad tests, whether it is overly fragile mocks, test duplication/coupling, or missed integration issues.

Some would perhaps say 'never encapsulate', but if you took them seriously, you would end up mocking the likes of RegExp and BigInteger, which can't be sensible.

Of course, this is something of a chicken-and-egg situation, as how you are going to test B always has at least some influence on how it is designed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.