Mockito – Verify arguments passed to mocks using ArgumentCaptor

In certain scenarios like if we have no control or handle of argument passed into a mock we can use Mockito ArgumentCaptor to verify if certain arguments where passed to mocks.

The complete source code used in this article can be cloned from github

package com.ourownjava.tdd.mockito.capture;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class EMailSender {
	
	private EMailService emailService;
	
	public void send(final String[] toAddresses, final String subject, final String content){
		emailService.send(new Email(toAddresses, subject, content));
	}
	
	public class Email {
		
		private Email(final String[] toAddresses, final String subject, final String content){
			this.toAdrresses = toAddresses;
			this.subject = subject;
			this.content = content;
		}
		
		private String [] toAdrresses;
		private String subject;
		private String content;
		
		
		public String[] getToAdrresses() {
			return toAdrresses;
		}
		public void setToAdrresses(String[] toAdrresses) {
			this.toAdrresses = toAdrresses;
		}
		public String getSubject() {
			return subject;
		}
		public void setSubject(String subject) {
			this.subject = subject;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}
	}

}

package com.ourownjava.tdd.mockito.capture;

import com.ourownjava.tdd.mockito.capture.EMailSender.Email;

/**
 * 
 * @author Sanju Thomas
 *
 */
public interface EMailService {

	public void send(final Email email);
}

package com.ourownjava.tdd.mockito.captor;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.ourownjava.tdd.mockito.capture.EMailSender;
import com.ourownjava.tdd.mockito.capture.EMailService;

/**
 * 
 * @author Sanju Thomas
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class TestEmailSender {
	
	@Mock
	private EMailService eMailService;

	@InjectMocks
	private EMailSender eMailSender;
	
	@Captor
	private ArgumentCaptor emailCaptor;
	
	@Before
	public void setUp(){
		
	}
	
	@Test
	public void shouldConstructEmailObjectAndSendEmail(){
		eMailSender.send(new String [] {"test@test.com"}, "test", "mockito argument captor test");
		verify(eMailService).send(emailCaptor.capture());
		assertArrayEquals(new String [] {"test@test.com"}, emailCaptor.getValue().getToAdrresses());
		assertEquals("test", emailCaptor.getValue().getSubject());
		assertEquals("mockito argument captor test", emailCaptor.getValue().getContent());
	}
	
	
}

Leave a comment

Your email address will not be published. Required fields are marked *