如何告诉 Junit/Mockito 等待 AndroidAnnotations 注入依赖项

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

我正在我的项目中使用 AndroidAnnotations,我想测试演示者。

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

@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 通过创建带注释的 class 的子 class 来工作,并在其中添加样板代码。然后,当您使用带注释的 classes 时,您将隐式(通过注入)或显式(通过访问生成的 class 交换生成的 classes,例如启动带注释的 Activity).

所以在这种情况下,要使其工作,您应该 运行 对测试 class LoginPresenterTest 进行注释处理,并且 运行 仅对测试进行注释处理生成 LoginPresenterTest_ class。这是可以做到的,但我建议更简洁的方法:

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

所以你有一个正常的测试class,你通过调用生成的工厂方法来实例化生成的bean。