Difference between Stub and Mock

Stubbing a method is all about replacing the method with code that returns a specified result (or perhaps raises a specified exception). Mocking a method is all about asserting that a method has been called (perhaps with particular parameters).

Using Moctio, set of two things will able to test the code. spy and mock.

On mock you set expectation and you use it on only mock objects. and significance of creating mock object is to substitute any dependency.

And for the objects you want to test obvious you cannot mock it. so here to stub we can use spy.

See below examples:

TicketAction ticketAction;
TicketDAO mockTicketDao;
User mockUser;

public void setupAction() {
ticketAction = spy(new TicketAction());

User mockUser = mock(User.class);


mockTicketDao = mock(TicketDAO.class);

public void listTicketShouldLoadTicketListForCurrentUser() {
ArrayList currentUserTickets = new ArrayList();

assertEquals(TicketAction.SUCCESS, ticketAction.listTickets());
assertSame(currentUserTickets, ticketAction.getTicketList());