PowerMock

PowerMock

优点:比 junit Jmock EasyMock Mockito 更强大。主要体现在可以对 static, final,   private 的方法 mock

做了个小例子针对非静态方法和静态方法的测试。

public class Astatic {

    public static String staString(String str){

        return str + "hello" ;

    }

}

 

public class BNonStatic {

    public String staString(String str){

        return str + "world" ;

    }

}

 

public class C {

    private BNonStatic B = new BNonStatic();

    public String c1(){

    String a = Astatic.staString ( "" );

             

    return B .staString(a);

    }

    public BNonStatic getB() {

        return B ;

    }

    public void setB(BNonStatic b) {

        B = b;

    }

   

}

 

现在要对 C 类中的 c1 方法进行单元测试,这个方法调用了一个静态的方法和一个非静态的方法。测试代码如下:

import junit.framework.Assert;

import org.easymock.EasyMock;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.powermock.api.easymock.PowerMock;

import org.powermock.core.classloader.annotations.PrepareForTest;

import org.powermock.modules.junit4.PowerMockRunner;

import org.powermock.api.easymock.annotation.Mock;

 

@RunWith (PowerMockRunner. class )

@PrepareForTest ({Astatic. class , C . class })

public class TestC {

   

    private C c = new C ();

   

    @Mock

    BNonStatic b ; // 定义要调用非静态方法的对象

   

    @Test

    public void testC(){

       

        // 静态方法的 mock

        PowerMock.mockStatic (Astatic. class );

        EasyMock.expect (Astatic.staString ( "" )).andReturn( "welcome" );

       

        // 非静态方法的 mock

        EasyMock.expect ( b .staString( "welcome" )).andReturn( "welcometohere" );

        PowerMock.replayAll ();

       

        c .setB( b );

        Assert.assertEquals ( "welcometohere" , c .c1());

        PowerMock.verifyAll ();

    }

}

你可能感兴趣的:(Powermock,单元测试,mock)