Wednesday, April 2, 2014

Difference between Stub and Mock object in Java Unit testing - JUnit

JUnit is the most popular framework for unit testing Java code. Unit testing is used to test a single programming unit e.g. a class or a method, in-fact many Java developer write unit test on per method basis. Stub and Mock objects are two concepts which helps during unit testing, they are not real object, but act like real object for unit testing purpose. By the way, If you are absolutely beginner in Java Unit testing then you can see this post to learn how to create JUnit test in Eclipse. Coming back to Stubs and Mocks, One reason of using Stub and Mock object is dependency of one unit into another. Since in real world, most unit doesn't work in isolation, they use dependent class and object to complete there task. One of the common testing approach to test a unit, which depends on other unit is by using Stubs and Mock objects. They help to reduce complexity, which may be require to create actual dependent object. In this tutorial, we will learn few basic difference between Stub and Mock object in Java Unit testing. This post is rather small to tackle this whole topic, at best it just provide an introduction. I would suggest to follow on some good books on Java Unit testing e.g. Pragmatic Unit Testing in Java. This is one of the must read book in Java Unit testing, and my personal favourite as well. Apart from teaching basics of Unit testing it also gives a nice overview of Mock objects and mock framework. Actually, from there, I came to know about EasyMock and jMock frameworks and how useful they can be. Even if you have been using JUnit and unit testing, you can learn a lot form this book. It's like learning from basics to best practices of Unit testing. Mockito is another useful library enables mocks creation, verification and stubbing.
Read more �

No comments:

Post a Comment