-
-
Save kikers25/1cd02b4033ef78602816 to your computer and use it in GitHub Desktop.
Test user service with jMock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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