【问题标题】:Mockito mock doesn't work properlyMockito 模拟无法正常工作
【发布时间】:2016-10-18 13:11:04
【问题描述】:

我有以下测试方法:

@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));
    }
}

测试以下类方法:

@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;
    }

据推测,当调用registerNewUser 时,它应该抛出一个异常,然后该方法将返回false,但是在调试时我看到没有抛出异常并且程序返回true。我做错了什么?

【问题讨论】:

  • 尝试删除这个` = new AccountManagerImpl(null);`
  • 我已经试过了。这无法完成,因为 Mockito 无法实例化接口,如果我这样做 @InjectMocks private AccountManagerImpl accountManager 我会得到同样的错误
  • 您的问题的答案在this page

标签: java testing junit mocking mockito


【解决方案1】:

首先你不应该实例化插入模拟的对象:

@InjectMocks
private AccountManager accountManager = new AccountManagerImpl(null);

改用这个:

@InjectMocks
private AccountManager accountManager;

如果你使用 Mockito 跑步者:

@RunWith(MockitoJUnitRunner.class)

您不应该直接注入模拟:

@Before
public void setup() {
    MockitoAnnotations.initMocks(this); //remove this line
}

最后一点:你的模拟没有意义,因为你的 register 方法中有一个局部变量:

AuthStorage authStorage = new AuthStorageImpl();
authStorage.registerNewUser(user);

这使得该类使用您的模拟对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2013-02-18
    • 2020-08-14
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多