Writing Better Tests With JUnit by Tobias Goeschel
For this week’s blog, I chose “Writing Better Tests With JUnit” by Tobias Goeschel. The blog contains different tips and suggestions on how to write a better test in JUnit. It also emphasized the idea that having a readable test code is at least as important as writing a readable production code and that the focus of the test must be on behavior instead of implementation. Another tip was to group tests by context. Grouping the tests by context would help us organize and focus on behaviors that should be grouped together. It would also help to understand the behavior more quickly and easily. Tobias also talked about enforcing the Single Assertion Rule. The rule was to use a single assertion if possible, but not it does necessarily mean that there could only be one assertion called, there are times when you would want to have multiple assertions. He also emphasized choosing meaningful names for the tests, it would be easier to know what the test is testing and eliminate unnecessary comments. The blog also talked about using other dependency injection frameworks like Spring to keep the tests fast and to avoid overly complex configurations. Lastly, he talked about avoiding test inheritance if possible since navigating the class hierarchy to get an idea of what is happening would make the test harder to understand.
I really find this blog useful. It stresses the idea of test behavior, not implementation. The blog also has some code in it where you can see how the tests are implemented. There are also different patterns that are useful when testing in the blog like the “Triple A” pattern which stands for “Arrange(preconditions and inputs) Act(things happen, methods are tested) Assert(see if the result was right)”. The other thing that I thought was thought-provoking is the use of inheritance. He said that it should be avoided if possible but when I read his explanation, it makes so much sense not to use inheritance. The way he emphasized that tests are as important as production code changes the way I think about coding now. I feel like writing test cases before writing the actual code might be a better approach to writing software.
From the blog CS@Worcester – Computer Science by csrenz and used with permission of the author. All other rights reserved by the author.