Mocking methods with return type void

Reading Time: < 1 minute

For a long while I’ve been looking forward to mocking void methods, I always thought that would be fairly impossible. After a long search online I’ve found it how to do it. So this example is from my work, it is a simple dummy method which creates a user on a 3rd party system.

import static org.mockito.Mockito.doNothing;
@Autowired
@Mock
private BusinessObjectsService boService;

private static final String testUserName = "TESTTESTTEST";
private static final String testUserNameLastName = "TEST";
private static final String testUserEmail = "TEST@TEST.COM";

@Before
	public void setUp() throws Exception {
                MockitoAnnotations.initMocks(this);
		when(boService.checkUserExistence(testUserName)).thenReturn(true);
		
	}
@Test
	public void createUserTest() {
//The method is being mocked!
		doNothing().when(boService).createUser(testUserName, testUserNameLastName,
 testUserNameLastName, testUserEmail);
		boolean userExistence = boService.checkUserExistence(testUserName);
		assertEquals(true, userExistence);
	}

outcome; success the test passed!