首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

(转)PowerMock运用

2012-12-27 
(转)PowerMock应用?import org.junit.Assertimport org.junit.Testimport org.junit.runner.RunWithimp

(转)PowerMock应用

?

import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.mockito.Mockito;import org.powermock.api.mockito.PowerMockito;import org.powermock.core.classloader.annotations.PrepareForTest;import org.powermock.modules.junit4.PowerMockRunner;@RunWith(PowerMockRunner.class)@PrepareForTest({ MyClass.class})public class StaticClassSampleTest {@Testpublic void testPrivateMethod() throws Exception {// 模拟 private的方法MyClass spy = PowerMockito.spy(new MyClass());PowerMockito.doReturn(3).when(spy, "private_method", 1);Assert.assertEquals(3, spy.test_private_method(1));PowerMockito.verifyPrivate(spy, Mockito.times(1)).invoke("private_method", 1);}@Testpublic void testStaticReturnMethod() throws Exception {// 模拟 静态有返回值的方法PowerMockito.mockStatic(MyClass.class);Mockito.when(MyClass.static_return_method()).thenReturn(2);Assert.assertEquals(2, MyClass.static_return_method());}@Testpublic void testVoidMethod() throws Exception {// 模拟 不执行void的方法MyClass spy = PowerMockito.spy(new MyClass());PowerMockito.doNothing().when(spy).void_method();spy.void_method();}@Testpublic void testStaticMethod1() throws Exception {// 模拟 不执行没参数的静态void的方法PowerMockito.mockStatic(MyClass.class);PowerMockito.doNothing().when(MyClass.class, "static_void_method");MyClass.static_void_method();}@Testpublic void testStaticMethod2() throws Exception {// 模拟 不执行带参数的静态void的方法PowerMockito.mockStatic(MyClass.class);PowerMockito.doNothing().when(MyClass.class, "staticMethod", "123");MyClass.staticMethod("123");PowerMockito.doNothing().when(MyClass.class, "staticMethod", Mockito.anyString());MyClass.staticMethod("456");}}class MyClass {final private int private_method(int a) {return a;}public int test_private_method(int a) {return private_method(a);}public static int static_return_method() {return 1;}void void_method() {throw new IllegalStateException("should not go here");}public static void static_void_method() {throw new IllegalStateException("should not go here");}public static void staticMethod(String a) {throw new IllegalStateException(a);}}

?

?

附上maven依赖?
<dependency>?
<groupId>org.mockito</groupId>?
<artifactId>mockito-all</artifactId>?
<version>1.8.5</version>?
</dependency>?
<dependency>?
<groupId>org.powermock</groupId>?
<artifactId>powermock-module-junit4</artifactId>?
<version>1.4.10</version>?
</dependency>?
<dependency>?
<groupId>org.powermock</groupId>?
<artifactId>powermock-api-mockito</artifactId>?
<version>1.4.10</version>?
</dependency>

?

转自:http://jh108020.iteye.com/blog/1462494

?

?

热点排行