UserRegistration { public void registerNewUser(String emailAddress) throws UserAlreadyRegisteredException, EmailFailedException { if (database.hasUser(emailAddress)) { throw new UserAlreadyRegisteredException(); } if(!emailSender.sendRegistrationEmail(new RegistrationEmail(emailAddress))) { throw new EmailFailedException(); } database.addUser(emailAddress); } UserRegistration(Database database, EmailSender emailSender); void registerNewUser(String emailAddress); void deleteUser(String emailAddress);  }
@Test public void shouldAddNewUserToDatabaseUsingAnyMatcherCasted() throws UserAlreadyRegisteredException, IOException { String emailAddress = "foo@example.com"; when(mockDatabase.hasUser(emailAddress)).thenReturn(false); when(mockEmailSender .sendRegistrationEmail((RegistrationEmail) any())) .thenReturn(true); testee.registerNewUser(emailAddress); Mockito.verify(mockDatabase).addUser(emailAddress); }
@Test public void shouldAddNewUserToDatabaseUsingAnyMatcherTypedOutside() throws UserAlreadyRegisteredException, IOException { String emailAddress = "foo@example.com"; when(mockDatabase.hasUser(emailAddress)).thenReturn(false); when(mockEmailSender .sendRegistrationEmail(ArgumentMatchers.<RegistrationEmail>any())) .thenReturn(true); testee.registerNewUser(emailAddress); Mockito.verify(mockDatabase).addUser(emailAddress); }
@Test public void shouldAddNewUserToDatabase() throws UserAlreadyRegisteredException, IOException { UserRegistration testee = new UserRegistration(mockDatabase, mockEmailSender); String emailAddress = "foo@example.com"; when(mockDatabase.hasUser(emailAddress)).thenReturn(false); when(mockEmailSender .sendRegistrationEmail(any(RegistrationEmail.class))) .thenReturn(true); testee.registerNewUser(emailAddress); Mockito.verify(mockDatabase).addUser(emailAddress); }
@Test(expected = UserAlreadyRegisteredException.class) public void shouldThrowExceptionAddingDuplicateEmail() throws UserAlreadyRegisteredException, EmailFailedException { Database mockDatabase = Mockito.mock(Database.class); EmailSender mockEmailSender = Mockito.mock(EmailSender.class); UserRegistration testee = new UserRegistration(mockDatabase, mockEmailSender); Mockito.when(mockDatabase.hasUser("foo@example.com")).thenReturn(true); testee.registerNewUser("foo@example.com"); }