Skip to content

Stub method calls

First create the mock Set by calling the org.mockito.Mockito.mock() method and passing the Set class to it as a parameter.

java
Set mockSet = mock(Set.class);

Now use the when() and thenReturn() method to define the behaviour of size() method as below:

java
when(mockSet.size()).thenReturn(10);

To check that the stubbing is done correctly call the size() method to see what it returns.

java
Assert.assertEquals(10, mockSet.size());

Below is the snippet of the whole test method:

java
@Test
public void stubMethodCalls() {

	Set mockSet = mock(Set.class);

	when(mockSet.size()).thenReturn(10);

	Assert.assertEquals(10, mockSet.size());
}

© 2023-2025 Maduranga Kannangara. Feel free to use or share this content. Attribution is appreciated but not required.