首页 > 代码库 > powerMock比easyMock和Mockito更强大(转)

powerMock比easyMock和Mockito更强大(转)

powerMock是基于easyMock或Mockito扩展出来的增强版本,所以powerMock分两种类型,如果你习惯于使用easyMock的,那你就下载基于easyMock的powerMock,反之你喜欢用mockito的话就下载另一种PowerMock.

    powerMock之所以说它更强大是因为它解决了easyMock和Mockito没有解决的问题,就是可以模仿static,private和final的方法。举例如下:

public class User{

private User user=new User();

public User(){

System.out.println("new User()");

}

public static User getInstance(){

   return user;

}

private String getHello(String h)

{

    return "hello "+h;

}

public String sayHello(String h)

{

     return getHello(h);

}

}

public classSubUser extends User{

public SubUser(){

System.out.println("new SubUser()");

}

}

测试用例,注意以下例子需要用junit4才能运行,如是不行的话建议重下一个jar包:junit-4.0.jar

 @RunWith(PowerMockRunner.class)//powerMock包里有两个PowerMockRunner,所以如果你的不能运行,请更换另一个试试 @PrepareForTest(User.class)  public class TestUser extends TestCase  {  User user;    //测试静态方法   @Test  public void testVerify()  {      mockStatic(User.class);     when(User.getInstance()).thenReturn(new SubUser());    User user=User.getInstance();

   verifyStatic();

}

//测试new一个对象

@Test      public void testWhenNew() {     try {     mockStatic(User.class);    whenNew(User.class).withNoArguments().thenReturn(new SubUser()) ;     user=new User();    verifyNew(User.class).withNoArguments();   } catch (Exception e) {    // TODO Auto-generated catch block    e.printStackTrace();   }

@Test//测试私有方法  public void testPrivate() {      User u = PowerMockito.spy(new User());             try {    PowerMockito.doReturn("hello world").when(u, "getHello", "hello");       System.out.println(u.sayHello("hello"));        

    PowerMockito.verifyPrivate(u, times(1)).invoke("getHello",  "hello");           } catch (Exception e) {    // TODO Auto-generated catch block    e.printStackTrace();   }          }

}

输出---------------------------------

new SubUser()

new SubUser()

 hello world

其它用法请参考这里:http://code.google.com/p/powermock/wiki/MockitoUsage13

以上为个人的一点经验,有可能表述有误,敬请指正

 

http://blog.csdn.net/Ant_cc/article/details/6977367

 http://dlwt.csdn.net/fd.php?i=686345406083133&s=8d1bea4adab5d744f78c6f60e13d3624

powerMock比easyMock和Mockito更强大(转)