Wednesday, May 23, 2012

What is Mocking in unit Testing?

Third Party Objects:

  • You have a class View that uses a third party class DBManager.
  • The View gets a name from DBManager, converts it into lower case and returns it. 
  • The DBManager contacts a Database and pulls the data for you.
  • But, you want to test View's functionality without being bothered about how DBManager actually gets those names.
 The code for above looks like this:

public class View {

 DBManager dbManager = new DBManager();
 public String processName(){
  String name = dbManager.getName();
  return  name.toLowerCase(); 
How do we test now? When we test we do not want the DBManager to contact the DB and get it for us.Its waaaay too an overhead for us to create a DB just for testing.
If you have guessed it, its right! You need to mock getName of dbManger into returning a String (which you may want to return different values for different different test cases??) that we can assert is giving us a correct lowercase value.

So the JUnit test looks something like this:

public class ViewTest {

 public void testProcessName(){
  /* Code to mock dbManager.getName 
   * to return "Anoop" goes here
  View view= new View();
  String name = view.processName();// here internally dbmanager returns "Anoop" because its mocked
  assertEquals("The returned name should be anoop","anoop",name);

So basically mocking is, as the name says, redefining the behaviour of an object or method to imitate or modify the original implementation to accomodate our test cases.

There are many mocking tools out there - JMockit, Mockito, EasyMock, PowerMock etc..

The two ways of mocking are either by the proxy apis or the instrumentation APIs. There's a lot we can talk about these two but that's for another post.

1 comment:

  1. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.
    Data Science Training in chennai at Credo Systemz | data science course fees in chennai | data science course in chennai quora | data science with python training in chennai