Tags


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;

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

User mockUser = mock(User.class);
when(mockUser.getUsername()).thenReturn(“some.email.id”);

doReturn(mockUser).when(ticketAction).getUser();

mockTicketDao = mock(TicketDAO.class);
ticketAction.setTicketDAO(mockTicketDao);
}

@Test
public void listTicketShouldLoadTicketListForCurrentUser() {
ArrayList currentUserTickets = new ArrayList();
when(mockTicketDao.getUserTickets(mockUser.getUsername())).thenReturn(currentUserTickets);

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

Advertisements