Java Mockito与异步任务

Java Mockito与异步任务,java,android,android-asynctask,mockito,Java,Android,Android Asynctask,Mockito,我正在使用Mockito编写一些测试。我有一个我想测试的类,它基本上通过AsyncTask将同步调用转换为异步调用 这是要测试的类: public class GetEntryImpl implements GetEntry { private final DataEntryRepository mDataEntryRepository; public GetEntryImpl() { this(new DataEntryRepositoryImpl());

我正在使用Mockito编写一些测试。我有一个我想测试的类,它基本上通过AsyncTask将同步调用转换为异步调用

这是要测试的类:

public class GetEntryImpl implements GetEntry {

    private final DataEntryRepository mDataEntryRepository;

    public GetEntryImpl() {
        this(new DataEntryRepositoryImpl());
    }

    public GetEntryImpl(@NonNull final DataEntryRepository repository) {
        mDataEntryRepository = repository;
    }

    @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);
                }
            }
        });
    }
}
第45行是测试的第一行:

mGetEntry.execute(1L, mCallbackArgumentCaptor.capture());

对于
回调
,您不需要
参数捕获器
,而需要模拟

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

@Mock
private Callback<DataEntry> mCallback;
@Mock
专用回调mCallback;

mockito打印错误,因为您在
验证
语句之外使用了
ArgumentCaptor
。您可以看到正确使用
ArgumentCaptor的示例。

对于
回调
,您不需要
ArgumentCaptor
,而需要模拟

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

@Mock
private Callback<DataEntry> mCallback;
@Mock
专用回调mCallback;

mockito打印错误,因为您在
验证
语句之外使用了
ArgumentCaptor
。您可以看到正确的
ArgumentCaptor
用法的示例。

您能否从堆栈跟踪中提供更多信息,比如mockito出了什么问题?添加了完整的堆栈跟踪。
DataEntryRepository
类的
getEntry()
方法的签名是什么?它是DataEntry getEntry(长id);您能否从堆栈跟踪中提供更多信息,比如mockito出了什么问题?添加了完整的堆栈跟踪。DataEntryRepository类的
getEntry()
方法的签名是什么?它是DataEntry getEntry(长id);