Leading-Edge Computer Programming Strategies - Mocking Your Objects
Implementing unit tests is actually something I did roughly four years in to my professional career as a computer programmer.
This unique relatively easy act produced a remarkable shift on the code that I was creating.
Solid calculations such as "the amount of bugs in the code" had confirmed that the concept of unit tests had done the duty of fabricating superior program code.
Now to expound on the subject of unit tests, today I must talk about mocking.
What on earth is Mocking? The term mocking is used to specify the process of limiting the coupling between your Objects (particularly at the time of unit testing).
This concept allows us to take every one of the collaborating Objects and mold them (quite simply) in to shell-like constructs designed to take away coupling.
For instance, let us say we have a UserService object which allows us to save and delete users.
We should test out our save and delete procedures and be sure they are always doing what we expect them to be doing...
but in order to test the UserService object, we'll need to instantiate and initialize a UserDao object (since this DAO object would be conducting the save/delete operations).
This causes a hassle because at this point we're not really "unit" testing, we're widening the range of our unit test to include 2 objects.
This invalidates the whole purpose of a unit test, so we must do something about this travesty! Hello Mocking.
You can 'mock' the DAO object that will allow your UserService object to interact with an empty shell of the DAO.
The UserService will still be capable of calling all of the functions, and you can even get fancy and supply your choice of return values from those called procedures.
This permits you to correctly map out the exact use-cases you intend to test within the UserService object.
The only caveat here is that when you mock an Object it's not as straight-forward as one might initially think.
Some complications arise when your Objects define private methods or have static/final methods.
In order to deal with these types of situations, you'll need to use more than just a basic mocking framework...
never fear, I shall outline what I use in a second! So, all in all, you'll have the ability to accurately test ONE single unit of your computer code and you will still be able to execute all your tests with impressive speed.
The mocking frameworks Personally i have tried recently that I would suggest highly include: - Mockito - Powermock