Sunday, 17 February 2013

Next generation Computer programming Techniques - Mocking your Objects


One topic which i have mentioned before was unit tests.  Implementing unit tests is something I did almost 4 years in to my professional job as a developer.  This unique straightforward act made a remarkable change on the program code which i was creating.  Concrete calculations like “the amount of issues in the program code” had proven that the idea of unit tests had done the job of making far better program code.  Now to expound on the subject of unit tests, today I wish to talk about mocking.

Just what is Mocking?


The term mocking can be used to specify the act of lessening the coupling between your Objects (such as during unit testing).  This idea allows us to take every one of the collaborating Objects and change them (quite simply) in to shell-like constructs that will eliminate coupling.  To illustrate, let’s say we have a UserService object that allows us to save and delete users.  We should test our save and delete methods and ensure that they are always doing what we anticipate them to be doing... but in order to run a test on the UserService object, we have to instantiate and initialize a UserDao object (since this DAO object would be conducting the save/delete functions).

This causes a complication because at this point we are not “unit” testing, we are broadening the scope of our unit test to incorporate 2 objects.  This defeats the entire purpose of a unit test, so we ought to do something about this travesty!

Hello Mocking.


It is possible to ‘mock’ the DAO object which will allow your UserService object to connect to an empty shell of the DAO.  The UserService will be able to call all of the functions, and you can even get fancy and supply the actual return values from the called methods.  This enables you to effectively create the precise use-cases you intend to test inside the UserService object.

Therefore, all in all, you will have the ability to accurately test A single unit of your code and you will still be able to run all of your tests with incredible speed.  The mocking frameworks Personally i have tried up to now i would suggest include:

- Mockito
- Powermock

To learn how to use these kinds of frameworks and other lessons on computer programming, you can check out the library of Java Video Tutorials available online.  I myself am an experienced Java developer and have produced a large number of video tutorials that explain this and many more extremely useful topics in computer programming at javavideotutorials.net.