普通Mock: Mock参数传递的对象
public boolean callArgumentInstance(File file) { return file.exists(); } @Test public void testCallArgumentInstance() { File file = PowerMockito.mock(File.class); ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.when(file.exists()).thenReturn(true); Assert.assertTrue(underTest.callArgumentInstance(file)); } |
说明:普通Mock不需要加@RunWith和@PrepareForTest注解。
Mock方法内部new出来的对象
public class ClassUnderTest { public boolean callInternalInstance(String path) { File file = new File(path); return file.exists(); } } @RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassUnderTest.class) public void testCallInternalInstance() throws Exception { File file = PowerMockito.mock(File.class); ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); PowerMockito.when(file.exists()).thenReturn(true); Assert.assertTrue(underTest.callInternalInstance("bbb")); } } |
说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。
Mock普通对象的final方法
public class ClassUnderTest { public boolean callFinalMethod(ClassDependency refer) { return refer.isAlive(); } } public class ClassDependency { public final boolean isAlive() { // do something return false; } } @RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassDependency.class) public void testCallFinalMethod() { ClassDependency depencency = PowerMockito.mock(ClassDependency.class); ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.when(depencency.isAlive()).thenReturn(true); Assert.assertTrue(underTest.callFinalMethod(depencency)); } } |
说明: 当需要mock final方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是final方法所在的类。
Mock普通类的静态方法
public class ClassUnderTest { public boolean callStaticMethod() { return ClassDependency.isExist(); } } public class ClassDependency { public static boolean isExist() { // do something return false; } } @RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassDependency.class) public void testCallStaticMethod() { ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.mockStatic(ClassDependency.class); PowerMockito.when(ClassDependency.isExist()).thenReturn(true); Assert.assertTrue(underTest.callStaticMethod()); } } |
说明:当需要mock静态方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是静态方法所在的类。
Mock RxJava
@RunWith(PowerMockRunner.class) @PrepareForTest(AppApi.class) public class SubmitPresenterTest { @Mock private SubmitContract.View mView; private SubmitContract.Presenter mPresenter; @Before public void init() { MockitoAnnotations.initMocks(this); mPresenter = new SubmitPresenter(mView); } @Test public void testLoadDataSuccess() { mockStatic(AppApi.class); //Observable.just(new InsuranceResultBean())会调用onNext方法 when(AppApi.getSubmitInsuranceResult(any(InsuranceInfoBean.class))).thenReturn(Observable.just(new InsuranceResultBean())); //Observable.<InsuranceResultBean>empty() 会直接调用onCompleted()方法 when(AppApi.getSubmitInsuranceResult(any(InsuranceInfoBean.class))).thenReturn(Observable.<InsuranceResultBean>empty()); mPresenter.submit(new InsuranceInfoBean()); verify(mView).onSuccess(any(InsuranceResultBean.class)); } @Test public void testLoadDataFail() { mockStatic(AppApi.class); //Observable.<InsuranceResultBean>error(new BusinessException(-3, "test fail"))会调用onError方法 when(AppApi.getSubmitInsuranceResult(any(InsuranceInfoBean.class))).thenReturn(Observable.<InsuranceResultBean>error(new BusinessException(-3, "test fail"))); mPresenter.submit(new InsuranceInfoBean()); verify(mView).showVerifyDialog(); } @Test public void testLoadDataFailToast() { mockStatic(AppApi.class); when(AppApi.getSubmitInsuranceResult(any(InsuranceInfoBean.class))).thenReturn(Observable.<InsuranceResultBean>error(new BusinessException(-4, "test fail"))); mPresenter.submit(new InsuranceInfoBean()); verify(mView).showVerifyDialog(); verify(mView).onToast(any(String.class)); } } |
Mock 私有方法
public class ClassUnderTest { public boolean callPrivateMethod() { return isExist(); } private boolean isExist() { return false; } } @RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassUnderTest.class) public void testCallPrivateMethod() throws Exception { ClassUnderTest underTest = PowerMockito.mock(ClassUnderTest.class); PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod(); PowerMockito.when(underTest, "isExist").thenReturn(true); Assert.assertTrue(underTest.callPrivateMethod()); } } |
说明:和Mock普通方法一样,只是需要加注解@PrepareForTest(ClassUnderTest.class),注解里写的类是私有方法所在的类。
Mock系统类的静态和final方法
public class ClassUnderTest { public boolean callSystemFinalMethod(String str) { return str.isEmpty(); } public String callSystemStaticMethod(String str) { return System.getProperty(str); } } @RunWith(PowerMockRunner.class) public class TestClassUnderTest { @Test @PrepareForTest(ClassUnderTest.class) public void testCallSystemStaticMethod() { ClassUnderTest underTest = new ClassUnderTest(); PowerMockito.mockStatic(System.class); PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb"); Assert.assertEquals("bbb", underTest.callJDKStaticMethod("aaa")); } } |
说明:和Mock普通对象的静态方法、final方法一样,只不过注解@PrepareForTest里写的类不一样 ,注解里写的类是需要调用系统方法所在的类。
PowerMock 简单实现原理
当某个测试方法被注解@PrepareForTest标注以后,在运行测试用例时,会创建一个新的org.powermock.core.classloader.MockClassLoader实例,然后加载该测试用例使用到的类(系统类除外)。
PowerMock会根据你的mock要求,去修改写在注解@PrepareForTest里的class文件(当前测试类会自动加入注解中),以满足特殊的mock需求。例如:去除final方法的final标识,在静态方法的最前面加入自己的虚拟实现等。
如果需要mock的是系统类的final方法和静态方法,PowerMock不会直接修改系统类的class文件,而是修改调用系统类的class文件,以满足mock需求。
测试RxJava
TestSubscriber用于单元测试,你可以用来执行断言,检查接收的事件,或者包装一个被mock的Subscriber。可以通过RxJava提供的Hook的方式修改线程为立即执行。
public Observable<String> getTestRxJava() { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } subscriber.onNext("test"); subscriber.onCompleted(); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } @Test public void testSync() { //通过Hook的方式修改主线程为immediate RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { @Override public Scheduler getMainThreadScheduler() { return Schedulers.immediate(); } }); //通过Hook的方式修改io线程为immediate RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() { @Override public Scheduler getIOScheduler() { return Schedulers.immediate(); } }); TestSubscriber<String> testSubscriber = new TestSubscriber<>(); mPresenter.getTestRxJava().subscribe(testSubscriber); testSubscriber.assertValue("test"); } |
图为TestSubscriber类中提供的方法。