mardi 18 octobre 2016

Mockito mock doesn't work properly

I have the following test function

@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 function would return false, but when debugging I see that the exception isn't throwed and the program returns true. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire