× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Java Unit Testing with Mockito

Yoni Levy
Oct 10, 2015
<p>Just to sum some points that came up:</p> <ul> <li>Unit tests as opposed to say Integration tests, are usually meant to test a single Class.</li> <li>Any class dependencies therefore should be removed from the equation (so that if a class dependency is buggy, the unit test won't be affected by it), which is done by mocking them away.</li> <li>Mocks are "fake" objects, copying all the public methods / members of the original class, while returning "default" values such as null for an object, or 0 for an int.</li> <li>Mocks can be told how they should behave, e.g. what a method should return when called on the mock. This is done with `when/then`.</li> <li>Mocks allow you to test your code's interaction with a dependency, by mocking the dependency and using `verify`.</li> <li>If the class under question is initializing a dependency directly (e.g calling `new Dependency()`), you won't be able to easily test interactions with that dependency. One easy way to fix that is to not initialize that dependency in the class, but rather receive it as a constructor argument, which then can be mocked in the test.</li> <li>One way to make sure a test is good, meaning it actually tests what it's supposed to test, is to momentarily comment out / edit the original code under test in a way that should make the test fail, and make sure the test indeed fails, in an appropraite manner.</li> <li>Naming unit tests properly is important and pretty easy, simply describe what is being tested, e.g. "throwsAnInvalidArgumentExceptionWhenIdIsIllegal"</li> <li>Ideally each test should only have one way to fail, meaning it tests a single thing.</li> </ul>
comments powered by Disqus