问题
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