使用带有事件侦听器的模拟对 MVP 进行单元测试


Android Studio 2.1.2

我想测试在 LoginModelImp 中是否实际调用了 UsernameError、onPasswordError 和 onSuccess 的回调。我不确定如何测试事件侦听器。但是,测试失败,因为永远不会调用这些函数。我正在用嘲笑来嘲笑他们,并试图验证他们。

这是我到目前为止的代码。

演示者界面

public interface LoginPresenterContract<LoginFragmentViewContract> {
    void validateCredentials();
    void attachView(LoginFragmentViewContract view);
    void detachView();
}

演示器实现

public class LoginPresenterImp implements LoginPresenterContract<LoginFragmentViewContract>, LoginModelContract.OnLoginCompletedListener {
    private LoginModelContract mLoginModelContract;
    private LoginFragmentViewContract mLoginFragmentView;
    public LoginPresenterImp(LoginModelContract loginModelContract) {
        mLoginModelContract = loginModelContract;
    }
    /*
     * LoginPresenterContact - implementation
     */
    @Override
    public void attachView(LoginFragmentViewContract view) {
        mLoginFragmentView = view;
    }
    @Override
    public void detachView() {
        mLoginFragmentView = null;
    }
    @Override
    public void validateCredentials() {
        if(mLoginModelContract != null) {
            mLoginModelContract.login(
                    mLoginFragmentView.getUsername(),
                    mLoginFragmentView.getPassword(),
                    LoginPresenterImp.this);
        }
    }
    /*
     * LoginModelContract.OnLoginCompletedListener - implementation
     */
    @Override
    public void onUsernameError() {
        if(mLoginFragmentView != null) {
            mLoginFragmentView.onLoginFailed("Incorrect username");
        }
    }
    @Override
    public void onPasswordError() {
        if(mLoginFragmentView != null) {
            mLoginFragmentView.onLoginFailed("Incorrect password");
        }
    }
    @Override
    public void onSuccess() {
        if(mLoginFragmentView != null) {
            mLoginFragmentView.onLoginSuccess();
        }
    }
}

模型接口

public interface LoginModelContract {
    interface OnLoginCompletedListener {
        void onUsernameError();
        void onPasswordError();
        void onSuccess();
    }
    void login(String username, String password, OnLoginCompletedListener onLoginCompletedListener);
}

模型实现

public class LoginModelImp implements LoginModelContract {
    /* Testing Valid username and passwords */
    private static String validUsername = "steve";
    private static String validPassword = "1234";
    @Override
    public void login(final String username,
                      final String password,
                      final OnLoginCompletedListener onLoginCompletedListener) {
        boolean hasSuccess = true;
        if(TextUtils.isEmpty(username) || !username.equals(validUsername)) {
        /* TEST onUsernameError() */
            onLoginCompletedListener.onUsernameError();
            hasSuccess = false;
        }
        if(TextUtils.isEmpty(password) || !password.equals(validPassword)) {
        /* TEST onPasswordError() */
            onLoginCompletedListener.onPasswordError();
            hasSuccess = false;
        }
        if(hasSuccess) {
        /* TEST onSuccess() */
            onLoginCompletedListener.onSuccess();
        }
    }
}

JUnit4 测试 with Mockito

public class LoginPresenterImpTest {
    private LoginFragmentViewContract mMockViewContract;
    private LoginModelContract mMockModelContract;
    private LoginModelContract.OnLoginCompletedListener mMockOnLoginCompletedListener;
    private LoginPresenterContract<LoginFragmentViewContract> mLoginPresenterContract;
    @Before
    public void setUp() throws Exception {
        mMockViewContract = Mockito.mock(LoginFragmentViewContract.class);
        mMockModelContract = Mockito.mock(LoginModelContract.class);
        mMockOnLoginCompletedListener = Mockito.mock(LoginModelContract.OnLoginCompletedListener.class);
        mLoginPresenterContract = new LoginPresenterImp(mMockModelContract);
        mLoginPresenterContract.attachView(mMockViewContract);
    }
    @Test
    public void shouldSuccessWithValidCredentials() {
        when(mMockViewContract.getUsername()).thenReturn("steve");
        when(mMockViewContract.getPassword()).thenReturn("1234");
        mLoginPresenterContract.validateCredentials();
        verify(mMockViewContract, times(1)).getUsername();
        verify(mMockViewContract, times(1)).getPassword();
        verify(mMockOnLoginCompletedListener, times(1)).onSuccess();
        verify(mMockOnLoginCompletedListener, never()).onPasswordError();
        verify(mMockOnLoginCompletedListener, never()).onUsernameError();
    }
}

有没有办法测试这个实现?

非常感谢您的任何建议,

测试类LoginPresenterImpTest是关于LoginPresenterImp类的测试,它应该只使用其实际实现和协作者的模拟。类LoginModelContract.OnLoginCompletedListenerLoginModelImp的合作者,所以在一个精心设计的、纯粹的LoginPresenterImp单元测试中,像你一样,它永远不会被调用是完全正常的。我建议的解决方案是单独测试LoginModelImp:

public class LoginModelImpTest {
    private LoginModelContract.OnLoginCompletedListener mMockOnLoginCompletedListener;
    private LoginModelImp loginModelImp;
    @Before
    public void setUp() throws Exception {
        mMockOnLoginCompletedListener = Mockito.mock(LoginModelContract.OnLoginCompletedListener.class);
        loginModelImp = new LoginModelImp();
    }
    @Test
    public void shouldSuccessWithValidCredentials() {
        loginModelImp.login("steve", "1234", mMockOnLoginCompletedListener);;
        verify(mMockOnLoginCompletedListener, times(1)).onSuccess();
        verify(mMockOnLoginCompletedListener, never()).onPasswordError();
        verify(mMockOnLoginCompletedListener, never()).onUsernameError();
    }
}

或者,您必须在LoginPresenterImpTest中使用LoginModelImp的实际实现并监视您的听众(即演示者本身)或配置模拟以使它们调用侦听器。这里有一个例子,但我不会使用这个:

public class LoginPresenterImpTest {
    private LoginFragmentViewContract mMockViewContract;
    private LoginModelContract mModelContract;
    private LoginModelContract.OnLoginCompletedListener mMockOnLoginCompletedListener;
    private LoginPresenterContract<LoginFragmentViewContract> mLoginPresenterContract;
    @Before
    public void setUp() throws Exception {
        mMockViewContract = Mockito.mock(LoginFragmentViewContract.class);
        mModelContract = new LoginModelImp();
        LoginPresenterImp spyPresenterImp = Mockito.spy(new LoginPresenterImp(mModelContract));
        mLoginPresenterContract = spyPresenterImp;
        mMockOnLoginCompletedListener = spyPresenterImp;
        mLoginPresenterContract.attachView(mMockViewContract);
    }
    @Test
    public void shouldSuccessWithValidCredentials() {
        when(mMockViewContract.getUsername()).thenReturn("steve");
        when(mMockViewContract.getPassword()).thenReturn("1234");
        mLoginPresenterContract.validateCredentials();
        verify(mMockViewContract, times(1)).getUsername();
        verify(mMockViewContract, times(1)).getPassword();
        verify(mMockOnLoginCompletedListener, times(1)).onSuccess();
        verify(mMockOnLoginCompletedListener, never()).onPasswordError();
        verify(mMockOnLoginCompletedListener, never()).onUsernameError();
    }
}

这归结为用户故事和用例之间的区别。 在这种情况下,您有 1 个用户故事(例如,"作为用户,我想登录,所以我提供了我的用户名和密码"),但实际上至少有 3 个用例:正确的用户名/正确的密码、正确的用户名/错误的密码、错误的用户名/正确的密码等。 作为一般的最佳实践,您希望测试与用例 1:1 对应,因此我建议这样:

 @Test
 public void shouldCompleteWithValidCredentials() {
    mMockModelContract.login("steve", "1234", 
                              mMockOnLoginCompletedListener);
    verify(mMockOnLoginCompletedListener, times(1)).onSuccess();     
 }
 @Test
 public void shouldNotCompleteWithInvalidUser() {
    mMockModelContract.login("wrong_user", "1234",
                               mMockOnLoginCompletedListener);
    verify(mMockOnLoginCompletedListener, 
                            times(1)).onUsernameError();      
 }
@Test
public void shouldNotCompleteWithInvalidPassword() {
    mMockModelContract.login("steve", "wrong_password", 
                         mMockOnLoginCompletedListener);
    verify(mMockOnLoginCompletedListener, times(1)).onPasswordError();
}

换句话说,对于测试 1,您正在尝试肯定地验证用户名和密码完成后是否调用了成功。 对于测试 2,您正在验证调用用户名错误的条件,对于测试 3,您正在验证调用 onPasswordError 的条件。 这三者都是有效的测试对象,您想要验证它们是否被调用是正确的,但您需要将它们视为不同的用例。

为了完整起见,我会验证 Wrong_User/Wrong_Password 上会发生什么,并验证如果出现 N 次Wrong_Password条件会发生什么(您需要阻止帐户吗?

希望这有帮助。 祝你好运。

我认为因为你在嘲笑LoginModelContractOnLoginCompletedListener你不能断言实际上调用了onUsernameErroronPasswordErroronSuccess,因为通过模拟LoginModelContract"真正的"登录方法(应该调用这些方法)不会被执行,而只会调用模拟的方法。您可以使用如下内容触发这些方法:

Mockito.doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        OnLoginCompletedListener listener = (OnLoginCompletedListener) args[2];
        listener.onUsernameError();
        return null;
    }
}).when(mMockModelContract).login(anyString(), anyString(), any(OnLoginCompletedListener.class)).thenAnswer();

但是,由于这样的测试是没有意义的,因为您显式调用了您要测试的内容。

在我看来,只测试LoginModelContract而不LoginFragmentViewContractLoginPresenterContract会更有意义。像这样:

public class LoginPresenterImpTest {
    private LoginModelContract mMockModelContract;
    private LoginModelContract.OnLoginCompletedListener mMockOnLoginCompletedListener;
    @Before
    public void setUp() throws Exception {
        mMockOnLoginCompletedListener = Mockito.mock(LoginModelContract.OnLoginCompletedListener.class);
        mMockModelContract = new LoginModelContract();
    }
    @Test
    public void shouldSuccessWithValidCredentials() {
        mMockModelContract.login("steve", "1234", mMockOnLoginCompletedListener);
        verify(mMockOnLoginCompletedListener, times(1)).onSuccess();
        verify(mMockOnLoginCompletedListener, never()).onPasswordError();
        verify(mMockOnLoginCompletedListener, never()).onUsernameError();
    }
}

我可能错过了你的观点,但你试过使用 PowerMock 吗?

需要以下依赖项:

  • testCompile "org.powermock:powermock-module-junit4:1.6.5"
  • testCompile "org.powermock:powermock-module-junit4-rule:1.6.5"
  • testCompile "org.powermock:powermock-api-mockito:1.6.5"
  • testCompile "org.powermock:powermock-classload-xstream:1.6.5"

然后以这种方式使用它:

@PowerMockIgnore({ "org.mockito.*", "android.*" })
@PrepareForTest(DownloadPresenterContract.Events.class)
public class DownloadModelTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();
    private DownloadPresenterContract.Events mockEvents;
    @Before
    public void setUp() throws Exception {
         this.mockEvents = PowerMockito.spy(new DownloadPresenterContract.Events());
         PowerMockito.whenNew(DownloadPresenterContract.Events.class)
                     .withNoArguments()
                     .thenReturn(this.mockEvents); 
    }
    @Test
    public void testStaticMocking() {
         //Do your logic, which should trigger mockEvents actions
         Mockito.verify(this.mockEvents, Mockito.times(1)).onDownloadSuccess();
         //Or use this:
         //PowerMockito.verifyPrivate(this.mockEvents, times(1)).invoke("onDownloadSuccess", "someParam");
}

}

相关内容

  • 没有找到相关文章

最新更新