Some classes simply require multiple dependencies that don’t always get used. When testing such a class, there are several options for supplying the constructor parameters that will not be used. I prefer to write tests that are as intention-revealing as possible.
To demonstrate, here is a simple example of a payment processing class. Think of the credit card machines that are found at the local grocery store. The basic flow is for the customer to approve the charge amount, then swipe their credit card or debit card and complete the transaction. Below, the PaymentProcessor is responsible for displaying the current charge amount to a user, verifying that they accept the amount, and then sending transaction information to the bank to request funds. Here is an example implementation:
The PaymentProcessor depends on IBankInformationReader, IBankService, and IUserVerification. If the user declines the payment amount, then processing should stop immediately. You can see this behavior above in lines 19-20.
Under this scenario, then PaymentProcessor should never interact with either the IBankInformationReader (used for reading the credit card swipe) or the IBankService (used for submitting the transaction). My preference is to pass null for the dependencies that shouldn’t be used, but to do so in an intention-revealing way. Here is an example:
Rather than simply passing the value null to the constructor in lines 12-13, I’ve used some local variables. This allows the test to clearly show intent. In this case, the test states that PaymentProcessor should never use the bank service or the card reader when the user declines the transaction. And, by using a null, we know that the test will fail if the PaymentProcessor tries to use those dependencies.
There is another option which is equally intention revealing but somewhat more noisy. We could use a mocking framework to generate the dependencies and then verify at the end of the test that they have never been used:
The problem that I have with this test is all the noise on lines 16-17. I would rather reveal this intention through some well-named variables.
Post Footer automatically generated by Add Post Footer Plugin for wordpress.