Most of the classes we come across have dependencies. and often times methods delegates some of the work to other methods in other classes, and we call these classes dependencies. When unit testing such methods, if we only used JUnit, our tests will also depend on those methods as well. We want the unit tests to be independent of all other dependencies.
- eg: we want to test the method
addCustomer
inCustomerService
class, and within thisaddCustomer
method, the save method of theCustomerDao
class is invoked. We don’t want to call the real implementation of theCustomerDao
save()
method for a few reasons: - We only want to test the logic inside the
addCustomer()
in isolation. - We may not yet have implemented it.
- We don’t want the unit test of the
addCustomer()
fail if there is a defect insave()
method in theCustomerDao
. - So we should some how mock the behavior of the dependencies. This is where mocking frameworks comes in to play.
- Mockito framework is what I use for just this and in this post we’ll see how to use mockito effectively to mock those dependencies.