Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Test user service with jMock
public class TestUserServiceWithJmock {
private static final Email EMAIL = new Email("user@company.com");
private static final User NO_FOUND_USER = new NoUser();
private static final User USER = null;
@Rule
public JUnitRuleMockery context = new JUnitRuleMockery();
@Mock
private UserDAO userdao;
@Mock
private EmailService emailservice;
private final class StubUserDaoThatDidNotFindTheUser implements UserDAO {
public User findUserBy(Email email) {
return NO_FOUND_USER;
}
public User createWith(Email email) {
// this isn't important for this example
return USER;
}
}
private final class SpyEmailService implements EmailService {
private boolean sentEmail = false;
public void sendEmailTo(User user) {
this.sentEmail = true;
}
public boolean wasSentEmail() {
return sentEmail;
}
}
@Test
public void //
should_send_an_email_when_a_user_was_created_with_our_own_spy_and_stub() throws Exception {
UserDAO stubUserDAO = new StubUserDaoThatDidNotFindTheUser();
SpyEmailService spyEmailService = new SpyEmailService();
UserService userService = new UserService(stubUserDAO, spyEmailService);
userService.findOrCreateWith(EMAIL);
assertThat(spyEmailService.wasSentEmail(), is(true));
}
@Test
public void //
should_send_an_email_when_a_user_was_created_with_jmock() throws Exception {
context.checking(new Expectations() {
{
oneOf(emailservice).sendEmailTo(with(any(User.class)));
allowing(userdao).findUserBy(with(any(Email.class)));
will(returnValue(NO_FOUND_USER));
allowing(userdao).createWith(with(any(Email.class)));
will(returnValue(USER));
}
});
UserService userService = new UserService(userdao, emailservice);
userService.findOrCreateWith(EMAIL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment