Reputation: 1857
I have the following test method:
@RunWith(MockitoJUnitRunner.class)
public class AccountManagerTest {
@InjectMocks
private AccountManager accountManager = new AccountManagerImpl(null);
@Mock
private AuthStorage authStorage;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
/* REGISTER TESTS */
@Test
public void test_whenRegister_withAlreadyExistingEmail_thenDoNotRegister() throws AuthStorageException {
String email = "[email protected]";
String name = "Foo";
String password = "123456";
String password2 = "123456";
doThrow(new AuthStorageException("Email already in use")).when(authStorage).registerNewUser(Matchers.any());
assertFalse(accountManager.register(email, name, password, password2));
}
}
that tests the following class method:
@Override
public Boolean register(String email, String name, String password, String password2) {
if (password.equals(password2)) {
try {
String pwd = hashPassword(password);
User user = new User(email, name, pwd);
AuthStorage authStorage = new AuthStorageImpl();
authStorage.registerNewUser(user);
return true;
} catch (NoSuchAlgorithmException | AuthStorageException e) {
return false;
}
}
// If passwords don't match
return false;
}
Supposedly, when calling registerNewUser
it should thow an exception and then the method would return false
, but when debugging I see that the exception isn't thrown and the program returns true
. What am I doing wrong?
Upvotes: 0
Views: 8510
Reputation: 4381
First of all you shouldn't instantiate the object where mocks are inserted:
@InjectMocks
private AccountManager accountManager = new AccountManagerImpl(null);
Instead, use this:
@InjectMocks
private AccountManager accountManager;
Then if you use Mockito runner:
@RunWith(MockitoJUnitRunner.class)
You shouldn't inject mocks directly:
@Before
public void setup() {
MockitoAnnotations.initMocks(this); //remove this line
}
And the last point: there is no point to your mocking because you have a local variable in your register method:
AuthStorage authStorage = new AuthStorageImpl();
authStorage.registerNewUser(user);
Which makes the class use your mocked object.
Upvotes: 5