Mockito is a fantastic mock library for Java. I’m fascinated by how easy
it is to use, compared to other things out there in the Java. To someone who is new to unit testing, the idea of mock objects can be
confusing to say the least. However, in the real world, software has dependencies. We have action
classes that depend on services and services that depend on data access
objects (DAOs) and the list goes on. The idea of unit testing is that we want to test our code without
testing the dependencies. This test allows you to verify that the code
being tested works, regardless of it's dependencies. The theory is that
if the code I write works as designed and my dependencies work as
designed, then they should work together as designed.
If you want to create unit tests to
test your code, having an Interface that defines the signature of your
Dao also lets you create a "mock" Dao object that you
can use in your tests.
As a template, it’s a good practice to view tests like a BDD style test.
The code below would be an example of this:
- Add the Mockito dependency to your pom.xml:
org.mockito
mockito-all
1.8.4
test
That’s it – all you need to know to get started. Mock objects are a very valuable tool in testing. They provide you with
the ability to test what you write without having to address dependency
concerns.