Quantcast
Channel: What's the difference between a mock & stub? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

Answer by Mikayil Abdullayev for What's the difference between a mock & stub?

$
0
0

Say you have a class named EmployeeService that you want to test and that has one dependency on an interface named EmployeeDao:

public class EmployeeService{   private EmployeeDao dao;   public EmployeeService(Dao dao){this.dao = dao;}   public String getEmployeeName(int id){     Employee emp = bar.goToDatabaseAndBringTheEmployeeWithId(id);     return emp != null?emp.getFullName:null;   }   //Further state and behavior}public interface EmployeeDao{  Employee goToDatabaseAndBringTheEmployeeWithId(int id);}

Inside your test class:

public class EmployeeServiceTest{   EmployeeService service;   EmployeeDao mockDao = Mockito.mock(EmployeeDao.class);//Line 3   @Before   public void setUp(){     service = new EmployeeService(mockDao);   }   //Tests   //....}

In the above test class in line 3, we say to the mocking framework (in this case Mockito) "Hey, Mockito, craft me an object that has the EmployeeDao functionality." The framework is going to create an object that has the method goToDatabaseAndBringTheEmployeeWithId but actually with no body. It's your job to instruct that mock what to do. This is a mock.

But you could also create a class that implements the EmployeeDao interface and use it in the test class instead:

public EmployeeDaoStub implements EmployeeDao{   public Employee goToDatabaseAndBringTheEmployeeWithId(int id){      //No trip to DB, just returning a dummy Employee object      return new Employee("John","Woo","123 Lincoln str");   }}

Inside your test class this time using stub instead of a mock:

public class EmployeeServiceTest{   EmployeeService service;   EmployeeDao daoStub = new EmployeeDaoStub();//Line 3   @Before   public void setUp(){     service = new EmployeeService(daoStub);   }   //Tests   //....}

So to wrap it all, stubs are the classes that you create(or somebody else does) specifically to imitate some dependency just for the sake of having the desired state. Yes, as all the other people state, it's mostly about a state Whereas mocks are typically created by a mocking framework and you have no idea what its guts look like. But with stubs you know what class you're going to get: It's the one you created.

Oh, btw, if your dependency is a class rather than an interface, you can just extend that class to create your stub.


Viewing all articles
Browse latest Browse all 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>