Java Mockito 正在使用真正的方法而不是使用模拟方法

Java Mockito is hitting real method rather than using mocked method

我的 mockito 方法正在调用真正的方法,而不是调用模拟方法。您的意见会有所帮助

Java代码。

public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final String domain){
        userDao = new UserDao(domain);
    }

    public IUser getExistingUser(){
            if (userDao == null) {
                throw new RuntimeException("userDao is null");
            }
            IUser existingUser = userDao.getExistingUser();
            if (existingUser == null) {
                throw new RuntimeException("ExistingUser is null");
            }
            return existingUser;
    }
}

这是我的 JUnit 测试代码。

    @Test
    public void testExistingUser() {
        UserDao mockUserDao = mock(UserDao.class);
        when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());
    }

    private UserDao getExistingTestUser(() {
        return ExistingUserImpl.Builder(). //withfield methods. build();
    }

我创建这个模拟对象只是为了测试目的。这只是 return 由 IUser 实现的模拟 MockedExistingUserImpl 对象。

public class MockedExistingUserImpl implements IUser {
    //fields
    //overriding getter methods for all fields
    //Builder for  ExistingUserImpl
}

每当我在我的代码中调用 userDao.getExistingUser() 时,我都期望 return 模拟的现有用户对象,但它正在使用真正的方法并且由于域连接而导致测试失败。我们不与 运行 Junits 建立域连接。任何意见表示赞赏。谢谢!

答案是阅读有关 Mockito 的教程并遵循该教程。您犯了一个典型的错误:您创建了一个模拟对象,但随后您没有做任何事情以便您的生产代码使用该模拟对象。

只是做一个 mock(YourClass) 不会神奇地将生产代码中的 new() 更改为 return 模拟实例。

您需要将模拟实例注入到被测代码中。例如通过使用@InjectMock 注释。

有关好的介绍,请参阅 https://www.baeldung.com/Mockito-annotations 示例。

注意:如现在所写,您将很难使用 Mockito 进行测试。由于直接调用 new(),您需要 PowerMock(ito) 来测试它。所以:学习如何使用 Mockito,然后重新编写您的生产代码以使其易于测试。 (转向 PowerMock 将是错误的策略)。

你的错误是破坏了'Dependency injection'原则。

不要使用 new 运算符 - 在上面的级别创建 UserDao 并使用注入。

public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final UserDao usedDao) {
        this.userDao = userDao;
    }

    public IUser getExistingUser() {
        if (userDao == null) {
            throw new RuntimeException("userDao is null");
        }
        IUser existingUser = userDao.getExistingUser();
        if (existingUser == null) {
            throw new RuntimeException("ExistingUser is null");
        }
        return existingUser;
    }
}

现在您可以通过以下方式测试您的代码:

@Test
public void testExistingUser() {
    UserDao mockUserDao = mock(UserDao.class);
    when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());

    CheckUser checkUser = new CheckUser(mockUserDao);
    IUser iUser = checkUser.getExistingUser();

    // assertions here
}

private UserDao getExistingTestUser(() {
    return ExistingUserImpl.Builder(). //withfield methods. build();
}