When Should Derick Specify Expected Parameters in Stub Methods?
Excuse the subject line. I wasn’t feeling creative. This post is in response to Derick’s post.
Derick asks if he should program his stubs with exact arguments per expected method call, and ends with “I know the answer is ‘it depends’”, but me - I’m a man of extremes. I don’t think it depends, and you should probably never use it (specifications), or, if you do “have to use it” – consider it a code smell for the tested code.
To me it’s like having more than one assert in you test: what happens if the method is called with “2” and not “1”? The test will fail? The stub will crash? Or is it that the real code will fail? If it is the latter – indeed you need to make sure the value is “1” and nothing else, in the scenario you test.
And you know how we do that, right?
Exactly – add another test. Add a test which checks that logic which renders that “1” argument works properly. If it really must be “1” – than we’re talking about functional requirement, and not an implementation detail, so that logic should be properly tested, and probably publicly exposed. If it doesn’t really have to be “1” there – than just don’t check it. Let the test fail on the real assertion.
And if we’re on that subject – don’t write tests with a mock object which expects a method to be “Called with exact arguments”. IT SMELLS! Separate the argument generation for the actual invocation and test them. Don’t write the simple test and disband the required refactoring – do the simple refactoring and then write the simpler test.