Spock: helper methods for assertions
Whenever I write tests, I always try to do it in such a way that when it eventually fails - the reason for that is clear and can be inferred based on the test output. In other words - when the test fails, it should tell you specifically what failed and why, without the need to use debugger or perform deep code analysis.
Examples below base on Spock 2.0.
â What not to do
Oftentimes, however, I encounter similar constructs in the code to the one below:
So whatâs the point, whatâs wrong with that? Letâs put it in the code and check the output:
Not helpful at all, is it? The only thing you know based on the output is that helperMethod
returned false, but itâs vague which exactly of the two conditions was the false one.
How to improve this?
â Do this instead
So now in the case of a failure, youâll see a neat output:
This now tells you exactly what happened and even shows you the value of a variable that undergoes the assertion. Well done!
đ§ âThe example is too made-upâŚâ
Yeah, youâre right, I totally feel you. The example was very simple for the sake of clarity. Letâs now look at the real-world one.
Letâs say that your code sends events and in the tests you want to intercept these events, store them in the memory and make assertions based on that. What did it look like when done in a bad way?
So⌠event was not sent, right? Thatâs what it says, at least. But what
.contains()
actually does is that itâs checking the equality of an object. So itâs not event
was not sent, but rather this exact event was not sent.
So basically there are two different situations possible: one is that no events were sent and the other one is that there were some events sent, but none of them matched our expected one. Then which one actually occurred? We donât know that, the test output does not provide any hint on it. We would need to run the debugger in order to track down the issue, which is costly and can take some time.
Letâs try the better way and see the benefits.
Well, it seems like your dogâs breed is a labrador retriever! If you want it to scare away the burglar, then you should reconsider your choice đ, youâll be better off having a Dobermann or something.
Anyway, the point is that having this output - you know exactly what happened by just looking at it! Isnât that great? Now that you know why the test failed, you can proceed with tracking down a bug in your production code, without wasting time on identifying the issue.
Take care about your logs - they should tell you the story.