Mockito和AsyncTasks

时间:2016-03-19 03:04:36

标签: java android android-asynctask mockito

我正在使用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);
                }
            }
        });
    }
}

这是我的考验:

public class GetEntryTest {
    private GetEntryImpl mGetEntry;
    @Mock
    private DataEntryRepository mRepository;
    @Captor
    private ArgumentCaptor<Callback> mCallbackArgumentCaptor;
    private DataEntry mDataEntry;

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

    @SuppressWarnings("unchecked")
    @Test
    public void testGetEntry_success() throws Exception {
        mGetEntry.execute(1L, mCallbackArgumentCaptor.capture());
        verify(mRepository).getEntry(eq(1L));
        Callback<DataEntry> callback = mCallbackArgumentCaptor.getValue();
        verify(callback).onResult(eq(mDataEntry));
    }
}

运行测试时,它会给我这个错误(编辑:完整堆栈跟踪):

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected here:

-> at com.xyz.interactor.GetEntryTest.testGetEntry_success(GetEntryTest.java:45)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.


    at com.xyz.interactor.GetEntryTest.testGetEntry_success(GetEntryTest.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)


Exception: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "AsyncTask #1"

Process finished with exit code 255

第45行是测试的第一行:

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

1 个答案:

答案 0 :(得分:2)

ArgumentCaptor不需要Callback,而是模拟。

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

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