Mockito:默认返回值

时间:2016-03-24 03:05:53

标签: java android mockito

根据documentation,非stubbed方法返回null。 我想测试一个在某些情况下应该返回“null”的方法,但是测试失败,异常表明没有调用该方法。

这是测试初始化​​函数:

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    mDataEntry = getFakeEntry();
    when(mRepository.getEntry(1L)).thenReturn(mDataEntry);
    mGetEntry = new GetEntryImpl(mRepository);
}

这是失败的测试:

@SuppressWarnings("unchecked")
@Test
public void testGetEntry_failure() throws Exception {
    mGetEntry.execute(2L, mCallback);
    verify(mRepository).getEntry(eq(2L));
    verify(mCallback).onError(anyString(), Mockito.any(Exception.class));
}

execute方法调用模拟对象mRepository函数getEntry(2L),我期望返回null。然而,这就是Mockito在我进行测试时告诉我的事情:

Wanted but not invoked:
mRepository.getEntry(2);
-> at com.xyz.interactor.GetEntryTest.testGetEntry_failure(GetEntryTest.java:54)
Actually, there were zero interactions with this mock.

我尝试添加

when(mRepository.getEntry(2L)).thenReturn(null);

到init函数,但没有区别。如果我返回一个有效的对象而不是null,那么测试会按预期失败,因为没有调用onError函数(因此当我指定一个有效的返回值时,将调用模拟对象的值2L的函数)。

如何让模拟对象为一组值返回null?

编辑:

这是测试中的函数的代码:

@Override
public void execute(final long id, final Callback<DataEntry> callback)  {
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            DataEntry dataEntry = mDataEntryRepository.getEntry(id);
            if (dataEntry != null) {
                callback.onResult(dataEntry);
            } else {
                callback.onError("TODO", null);
            }
        }
    });
}

作为参考,成功测试有效:

@SuppressWarnings("unchecked")
@Test
public void testGetEntry_success() throws Exception {
    mGetEntry.execute(1L, mCallback);
    verify(mRepository).getEntry(eq(1L));
    verify(mCallback).onResult(eq(mDataEntry));
}

1 个答案:

答案 0 :(得分:1)

我认为问题不在于Mockito默认值/返回null。

我写了一个修改过的SSCCE,测试运行正常。我没有android API,所以我无法使用AsynchTask.execute()。据我所知,这段代码将在一个单独的线程中运行,因此您可能无法保证在调用verify之前运行代码。如果您取出AsynchTask并按如下方式执行execute,它是否仍会失败?是否有可能在执行中抛出异常?

    public void execute( final long id, final Callback<DataEntry> callback)  {
        DataEntry dataEntry = mDataEntryRepository.getEntry(id);
        if (dataEntry != null) {
            callback.onResult(dataEntry);
        } else {
            callback.onError("TODO", null);
        }
    }