本文介绍了如何告诉Junit/Mockito等待AndroidAnnotations注入依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用AndroidAnnotations,并且想要测试演示者.

I am using AndroidAnnotations in my project and I want to test a presenter.

运行测试套件,显然在注入完成之前调用@Test方法,因为每当尝试在测试代码中使用LoginPresenter时,我都会得到NullPointerException.

The test suite runs and @Test methods are apparently called before the injection has finished, because I get NullPointerException whenever I try to use the `LoginPresenter in my test code.

@RunWith(MockitoJUnitRunner.class)
@EBean
public class LoginPresenterTest {

    @Bean
    LoginPresenter loginPresenter;

    @Mock
    private LoginView loginView;

    @AfterInject
    void initLoginPresenter() {
        loginPresenter.setLoginView(loginView);
    }

    @Test
    public void whenUserNameIsEmptyShowErrorOnLoginClicked() throws Exception {
        when(loginView.getUserName()).thenReturn("");
        when(loginView.getPassword()).thenReturn("asdasd");
        loginPresenter.onLoginClicked();
        verify(loginView).setEmailFieldErrorMessage();
    }
}

推荐答案

AndroidAnnotations通过创建带注释的类的子类并在其中添加样板代码来工作.然后,当您使用带注释的类时,将隐式地(通过注入)或显式地(通过访问生成的类,例如,启动带注释的Activity)交换生成的类.

AndroidAnnotations works by creating subclasses of the annotated classes, and adds boilerplate code in them. Then when you use your annotated classes, you will swap the generated classes in either implicitly (by injecting) or explicitly (by accessing a generated class, for example starting an annotated Activity).

因此,在这种情况下,要使其正常运行,您应该已经在测试类LoginPresenterTest上运行了注释处理,并且仅在生成的LoginPresenterTest_类上运行了测试.可以做到这一点,但我建议采用一种更清洁的方法:

So in this case to make it work, you should have run the annotation processing on the test class LoginPresenterTest, and run the test only on the generated LoginPresenterTest_ class. This can be done, but i suggest a cleaner way:

@RunWith(MockitoJUnitRunner.class)
public class LoginPresenterTest {

    private LoginPresenter loginPresenter;

    @Mock
    private LoginView loginView;

    @Before
    void setUp() {
        // mock or create a Context object
        loginPresenter = LoginPresenter_.getInstance_(context);
    }

    @Test
    public void whenUserNameIsEmptyShowErrorOnLoginClicked() throws Exception {
        when(loginView.getUserName()).thenReturn("");
        when(loginView.getPassword()).thenReturn("asdasd");
        loginPresenter.onLoginClicked();
        verify(loginView).setEmailFieldErrorMessage();
    }
}

因此,您有一个普通的测试类,并且可以通过调用生成的工厂方法来实例化生成的bean.

So you have a normal test class, and you instantiate the generated bean by calling the generated factory method.

这篇关于如何告诉Junit/Mockito等待AndroidAnnotations注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:43