How to tell Junit/Mockito to wait for AndroidAnnotations to inject the dependenices

左心房为你撑大大i 提交于 2019-12-12 03:44:44

问题


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

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

回答1:


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).

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

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



来源:https://stackoverflow.com/questions/36064047/how-to-tell-junit-mockito-to-wait-for-androidannotations-to-inject-the-dependeni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!