android - 断言 Mockito 模拟对象被设置为 null

标签 android junit mockito

我正在使用 Mockito 进行 JUnit 测试,但一直在解决断言问题。我正在创建一个模拟对象,然后使用模拟对象创建一个演示者对象。

@Mock
Object mFooBar;

private FooPresenter mFooPresenter;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    mFooPresenter = new FooPresenter(mFooBar);

}

在演示者的 onDestroy() 方法中,我清空了对象。

public FooPresenter(Object fooBar) {
    mFooBar = fooBar;
}

@Override
public void onDestroy() {
    mFooBar = null;
}

然后,当我尝试在我的 FooPresenterTest 中为 mFooBar 断言 Null 时,它失败了,因为它不为空。

@Test
public void testThatObjectsAreNullifiedInOnDestroy() throws Exception {
    fooPresenter.onDestroy();

    assertNull(mFooBar);
}

这失败了

Expected :<null>
Actual :mFooBar

那么我的问题是,与我为运行测试而实例化的对象相比,如何处理对测试类中模拟对象的引用?为什么 assertNull 在本应设置为 null 时却失败了?

最佳答案

@kerseyd27,

从你的测试名称 testThatObjectsAreNullifiedInOnDestroy 看来,你正在寻找验证注入(inject)的 mFooBar 对象在演示者被销毁时被你的演示者释放。

首先,直接回答你的问题:

how are the references handled to the mocked objects in my test class compared to the object I instantiated to run the test?

我会让这些答案( link 1link 2 )不言自明,但解释它与您的问题有何关联。模拟对象在 Test 类中实例化并按值传递到 FooPresenterFooPresenter.mFooBar 是指向模拟对象的独立引用(属于演示者)。在调用onDestroy 方法之前,TestClass.mFooBarfooPresenter.mFooBar 引用相同的对象(模拟对象),但它们是两个不同的对象对此对象的引用。

Why does assertNull fail when it should have been set to null?

您断言 Test.mFooBar(属于 Test 类)为空。 Test.mFooBar 是在测试设置中创建的,但此变量从未设置为 null。另一方面,fooPresenter.mFooBar 变量 显式设置为 null。同样,虽然这些变量指向同一个对象,但引用本身并不相同。

如果您希望确保 fooPresetner.mFooBar 为 null,您可以将其设为包本地或使用属性公开它。仅出于测试目的而这样做通常是不受欢迎的。

如果您希望确保在构造函数中对 mFooBar 对象执行某些操作,您可以编写如下测试:

public class TestClass {

    interface FooBar {
        void releaseSomething();
    }

    @Rule
    public MockitoRule r = MockitoJUnit.rule();

    @Mock
    FooBar mFooBar;

    @Test
    public void testThatObjectsAreNullifiedInOnDestroy() {
        new FooPresenter(mFooBar).onDestroy();
        verify(mFooBar).releaseSomething();
    }

    class FooPresenter {
        private FooBar mFooBar;

        public FooPresenter(FooBar fooBar) {this.mFooBar = fooBar;}

        @Override
        void onDestroy() {
            mFooBar.releaseSomething();
            mFooBar = null;
        }
    }
}

祝你好运,测试愉快!

关于android - 断言 Mockito 模拟对象被设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874996/

相关文章:

java - 如何使用 Mockito 验证 final方法的执行?

java - Mockito when().thenReturn() 抛出 nullpointerExceptions

android - Google Maps Fragment 在 fragment 内返回 null

java - 用于目录压缩器的 JUnit

java - onClick() 更改图像

java - 如何在我的代码中对 try catch block 进行 Junit 测试

java - Junit 4 测试覆盖率

java - 如何将对象传递给 UnitTest 类中被测试的类?

android - 如何使用 Picasso 将位图加载到 ImageView 中

android - 如何在滑动 ViewPager2 选项卡时重新创建或刷新 fragment