【问题标题】:How to tell Junit/Mockito to wait for AndroidAnnotations to inject the dependenices如何告诉 Junit/Mockito 等待 AndroidAnnotations 注入依赖项
【发布时间】:2016-03-17 14:50:34
【问题描述】:

我在我的项目中使用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();
    }
}

【问题讨论】:

    标签: android junit mockito android-annotations


    【解决方案1】:

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

    所以在这种情况下,为了让它工作,你应该在测试类LoginPresenterTest上运行注释处理,并且只在生成的LoginPresenterTest_类上运行测试。这可以做到,但我建议一种更清洁的方式:

    @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。

    【讨论】:

    • 我如何获得对上下文对象的访问权限(在 LoginPresenterTest 类中) - 抱歉,这是我第一次进行单元测试
    • 我扩展了InstrumentationTestCase 并在getInstance_(Context context) 中尝试了getInstrumentation().getContext(),但我在那条线上得到了一个N​​PE
    • 我建议阅读答案here。但是您应该以这种方式获得上下文。实际上什么对象是空的,是仪器还是它的上下文?
    • 我什么都试过了,我也试过了。没有上下文。在运行测试之前是否有其他方法可以等待注入通过?
    • 该上下文应该可用。您确定您在设备或模拟器上正确运行测试吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2010-11-08
    • 2018-03-06
    • 2010-10-28
    • 2019-08-13
    相关资源
    最近更新 更多