JosepRivaille JosepRivaille -3 years ago 121
Java Question

Mockito mock doesn't work properly

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 = "foo@bar.com";
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download