Mockito测试:验证静态方法是否在片段内调用

时间:2016-06-22 10:32:19

标签: android mockito powermockito

我有一个片段,它从另一个Util类调用静态方法。

 public class DummyFragment extends Fragment {

    public void dummyMethodCall(){
      UtilClass.dummyStaticMethod(Arg arg);
    }

 }

如何使用PowerMockito验证在Mockito测试中是否已调用UtilClass.dummyStaticMethod()?以下是我当前的测试:

    @RunWith(RobolectricGradleTestRunner.class)
    @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
    @Config(constants = BuildConfig.class, sdk = 19, packageName = "com.dummy.package", application = DummyApplication.class)
    @PrepareForTest({UtilClass.class})
    public class FragmentTest {

    private DummyFragment mDummyFragment;

    @Rule
    public PowerMockRule rule = new PowerMockRule();

    @Before
    public void setUp() {
        mDummyFragment = new DummyFragment();
    }

    @Test
        public void dummyMethodCall_success() {

            PowerMockito.mockStatic(UtilClass.class);
            mDummyFragment.dummyStaticMethod();
            PowerMockito.verifyStatic();
        }

    }

错误日志:

java.lang.IllegalStateException: Failed to transform class with name android.app.Activity. Reason: android.app.LoaderManagerImpl

at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:267)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:180)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at javassist.runtime.Desc.getClassObject(Desc.java:43)
at javassist.runtime.Desc.getClassType(Desc.java:152)
at javassist.runtime.Desc.getType(Desc.java:122)
at javassist.runtime.Desc.getType(Desc.java:78)
at com.dummy.package.DummyFragmentTest.setUp(DummyFragment.java:60)
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.RunBefores.evaluate(RunBefores.java:24)

1 个答案:

答案 0 :(得分:1)

如果要检查它是否在实际测试中调用,可以在您的UtilClass中添加一个布尔静态成员,您在dummyStaticMethod()中设置为true,然后在测试中调用后检查该值。

如果您只想检查它是否有用于调试目的,可以在调试模式下运行并在dummyStaticMethod中设置断点,或者将System.out.print添加到方法中。