Instantly share code, notes, and snippets.

What would you like to do?
An example of behavior verification + argument capture with Mockito (on TestNG)
package com.pillartechnology.mail;
import java.util.Date;
public class Email {
private String domain;
private String user;
private String body;
public String getDomain() {
return domain;
public void setDomain(String domain) {
this.domain = domain;
public String getUser() {
return user;
public void setUser(String user) {
this.user = user;
public String getBody() {
return body;
public void setBody(String body) {
this.body = body;
package com.pillartechnology.mail;
public interface ExternalMailSystem {
public void send(String domain, String user, String body);
public void send(Email email);
package com.pillartechnology.mail;
public class MailDeliverer {
private ExternalMailSystem externalMailSystem;
public void deliver(String address, String body) {
Email email = new Email();
applyUserAndDomainUsingProvidedAddress(address, email);
private void applyUserAndDomainUsingProvidedAddress(String address, Email email) {
//TODO - refactor this into the Email class (constructor? smart accessor?)
String[] addressComponents = address.split("@");
package com.pillartechnology.mail;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class MailDelivererTest {
@InjectMocks private MailDeliverer subject = new MailDeliverer();
@Mock private ExternalMailSystem externalMailSystem;
@Captor private ArgumentCaptor<Email> emailCaptor;
public void injectDoubles() {
public void sendsEmailByConstructingEmailObject() {
String expectedUser = "tim";
String expectedDomain = "";
String expectedBody = "Hi Tim!";
Email email = emailCaptor.getValue();
@Test(enabled=false) //"WIP - We're converting to the service method that sends an Email object"
public void sendsEmailBySplittingAddress() {
String expectedBody = "Hi Tim!";
verify(externalMailSystem).send("","tim", expectedBody);

This comment has been minimized.

auric-mason commented Feb 10, 2016

Thank you so much for publishing this, I was having a hard time following the api docs, but this explained it very clearly.


This comment has been minimized.

vivekach commented Jan 24, 2017

Thank you so much.. Surely it will help me.. :)


This comment has been minimized.

chaminiPrashakthi commented Jan 29, 2018

Great Example !!!!


This comment has been minimized.

jeanPokou commented Nov 16, 2018

Nice example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment