Skip to content

Instantly share code, notes, and snippets.

@kikers25
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikers25/1cd02b4033ef78602816 to your computer and use it in GitHub Desktop.
Save kikers25/1cd02b4033ef78602816 to your computer and use it in GitHub Desktop.
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