PowerMock 模拟 MoreAsserts

PowerMock mocks MoreAsserts

我正在 android studio 中编写单元测试并使用 PowerMock

测试看起来像这样

@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest({Typeface.class})
public class ExtendedTextViewTest {

    ...

    @Test
    public void ctor_context_attributeSet_ShouldSetTypeface() throws Exception {
        // Act
        final LinkedList<Typeface> actualTypefaces = new LinkedList<Typeface>();
        ExtendedTextView textView = spy(new ExtendedTextView(contextMock, attributeSet) {
            @Override
            public void setTypeface(Typeface typeface) {
                actualTypefaces.add(typeface);
            }
        });

        // Assert
        MoreAsserts.assertEquals(new Typeface[]{typefaceMock}, actualTypefaces.toArray());
        verify(typedArrayMock, times(1)).recycle();
    }

}

当我 运行 测试时出现错误:

java.lang.RuntimeException: Method assertEquals in android.test.MoreAsserts not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.test.MoreAsserts.assertEquals(MoreAsserts.java)
    at com.loka.loka.common.ExtendedTextViewTest.ctor_context_attributeSet_ShouldSetTypeface(ExtendedTextViewTest.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)

似乎 mockito 在没有我要求的情况下模拟了 MoreAsserts...我错过了什么?

谢谢, 斯拉瓦

好的,搜索后我找到了答案...... MoreAsserts 是一个 android sdk class (android.test.MoreAsserts)

当 运行 单元测试时,android sdk 没有加载,而是所有 classes 都被一个抛出异常的实现存根,包括 MoreAsserts..

所以我需要用 JUNit 断言替换断言:Assert.assertArrayEquals

Assert.assertArrayEquals(new Typeface[]{typefaceMock}, actualTypefaces.toArray());

希望对大家有所帮助=]