PowerMockito(PowerMock用法)


網絡上大部分是powermock 的用法, 

PowerMock有兩個重要的注解:

      –@RunWith(PowerMockRunner.class)  

      –@PrepareForTest( { YourClassWithEgStaticMethod.class })

但是powermockito @PrepareForTest( { YourClassWithEgStaticMethod.class }) 是在使用時 每個test case 方法中按需添加的。 @RunWith(PowerMockRunner.class)  必須添加到類名頭。

摘自:

http://blog.csdn.net/knighttools/article/details/44630975

 

一、為什么要使用Mock工具

      在做單元測試的時候,我們會發現我們要測試的方法會引用很多外部依賴的對象,比如:(發送郵件,網絡通訊,遠程服務, 文件系統等等)。 而我們沒法控制這些外部依賴的對象,為了解決這個問題,我們就需要用到Mock工具來模擬這些外部依賴的對象,來完成單元測試。

      二、為什么要使用PowerMock

      現如今比較流行的Mock工具如jMock EasyMock 、Mockito等都有一個共同的缺點:不能mock靜態、final、私有方法等。而PowerMock能夠完美的彌補以上三個Mock工具的不足。

      三、PowerMock簡介

      PowerMock是一個擴展了其它如EasyMock等mock框架的、功能更加強大的框架。PowerMock使用一個自定義類加載器和字節碼操作來模擬靜態方法,構造函數,final類和方法,私有方法,去除靜態初始化器等等。通過使用自定義的類加載器,簡化采用的IDE或持續集成服務器不需要做任何改變。熟悉PowerMock支持的mock框架的開發人員會發現PowerMock很容易使用,因為對於靜態方法和構造器來說,整個的期望API是一樣的。PowerMock旨在用少量的方法和注解擴展現有的API來實現額外的功能。目前PowerMock支持EasyMock和Mockito。

      四、PowerMock入門    

      PowerMock有兩個重要的注解:

      –@RunWith(PowerMockRunner.class)

      –@PrepareForTest( { YourClassWithEgStaticMethod.class })

      如果你的測試用例里沒有使用注解@PrepareForTest,那么可以不用加注解@RunWith(PowerMockRunner.class),反之亦然。當你需要使用PowerMock強大功能(Mock靜態、final、私有方法等)的時候,就需要加注解@PrepareForTest。

      五、PowerMock基本用法

      (1) 普通Mock: Mock參數傳遞的對象

 

      測試目標代碼:

1 public boolean callArgumentInstance(File file) {
2  
3      return file.exists();
4  
5 }

     測試用例代碼: 

01 @Test 
02 public void testCallArgumentInstance() {
03   
04     File file = PowerMockito.mock(File.class); 
05  
06     ClassUnderTest underTest = new ClassUnderTest();
07    
08     PowerMockito.when(file.exists()).thenReturn(true);
09   
10     Assert.assertTrue(underTest.callArgumentInstance(file)); 
11 }

      說明:普通Mock不需要加@RunWith和@PrepareForTest注解。

       (2)  Mock方法內部new出來的對象

       測試目標代碼:

01 public class ClassUnderTest {
02  
03     public boolean callInternalInstance(String path) { 
04  
05         File file = new File(path); 
06  
07         return file.exists(); 
08  
09     
10 }

       測試用例代碼:    

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassUnderTest.class
06     public void testCallInternalInstance() throws Exception { 
07  
08         File file = PowerMockito.mock(File.class); 
09  
10         ClassUnderTest underTest = new ClassUnderTest(); 
11  
12         PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); 
13          
14         PowerMockito.when(file.exists()).thenReturn(true); 
15  
16         Assert.assertTrue(underTest.callInternalInstance("bbb")); 
17     
18 }

      說明:當使用PowerMockito.whenNew方法時,必須加注解@PrepareForTest和@RunWith。注解@PrepareForTest里寫的類是需要mock的new對象代碼所在的類。

     (3) Mock普通對象的final方法

 

     測試目標代碼:

1 public class ClassUnderTest {
2  
3     public boolean callFinalMethod(ClassDependency refer) { 
4  
5         return refer.isAlive(); 
6  
7     
8 }

 

01 public class ClassDependency {
02      
03     public final boolean isAlive() {
04  
05         // do something 
06  
07         return false
08  
09     
10 }

       測試用例代碼:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassDependency.class
06     public void testCallFinalMethod() {
07  
08         ClassDependency depencency =  PowerMockito.mock(ClassDependency.class);
09   
10         ClassUnderTest underTest = new ClassUnderTest();
11   
12         PowerMockito.when(depencency.isAlive()).thenReturn(true);
13   
14         Assert.assertTrue(underTest.callFinalMethod(depencency));
15   
16     }
17 }

      說明: 當需要mock final方法的時候,必須加注解@PrepareForTest和@RunWith。注解@PrepareForTest里寫的類是final方法所在的類。 

      (4) Mock普通類的靜態方法

      測試目標代碼:

1 public class ClassUnderTest {
2  
3     public boolean callStaticMethod() {
4   
5         return ClassDependency.isExist(); 
6  
7     }  
8 }

 

01 public class ClassDependency {
02     
03     public static boolean isExist() {
04  
05         // do something 
06  
07         return false
08  
09     
10 }

      測試用例代碼:

 

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassDependency.class
06     public void testCallStaticMethod() {
07   
08         ClassUnderTest underTest = new ClassUnderTest();
09   
10         PowerMockito.mockStatic(ClassDependency.class); 
11  
12         PowerMockito.when(ClassDependency.isExist()).thenReturn(true);
13   
14         Assert.assertTrue(underTest.callStaticMethod());
15   
16     }
17 }

      說明:當需要mock靜態方法的時候,必須加注解@PrepareForTest和@RunWith。注解@PrepareForTest里寫的類是靜態方法所在的類。

      (5) Mock 私有方法

 

      測試目標代碼: 

01 public class ClassUnderTest {
02  
03     public boolean callPrivateMethod() { 
04  
05         return isExist(); 
06  
07     }       
08  
09     private boolean isExist() {
10    
11         return false
12  
13     }
14 }

 

     測試用例代碼:  

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04     @Test 
05     @PrepareForTest(ClassUnderTest.class
06     public void testCallPrivateMethod() throws Exception { 
07  
08        ClassUnderTest underTest = PowerMockito.mock(ClassUnderTest.class); 
09  
10        PowerMockito.when(underTest.callPrivateMethod()).thenCallRealMethod(); 
11  
12        PowerMockito.when(underTest, "isExist").thenReturn(true);
13    
14        Assert.assertTrue(underTest.callPrivateMethod());
15   
16     }
17 }

       說明:和Mock普通方法一樣,只是需要加注解@PrepareForTest(ClassUnderTest.class),注解里寫的類是私有方法所在的類。 

       (6) Mock系統類的靜態和final方法 

        測試目標代碼:   

01 public class ClassUnderTest {
02  
03     public boolean callSystemFinalMethod(String str) {
04  
05         return str.isEmpty(); 
06  
07     
08  
09     public String callSystemStaticMethod(String str) {
10   
11         return System.getProperty(str); 
12  
13     }
14 }

      測試用例代碼:

01 @RunWith(PowerMockRunner.class
02 public class TestClassUnderTest {
03  
04   @Test 
05   @PrepareForTest(ClassUnderTest.class
06   public void testCallSystemStaticMethod() { 
07  
08       ClassUnderTest underTest = new ClassUnderTest(); 
09  
10       PowerMockito.mockStatic(System.class); 
11  
12       PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb");
13    
14       Assert.assertEquals("bbb", underTest.callJDKStaticMethod("aaa")); 
15  
16   
17 }

      說明:和Mock普通對象的靜態方法、final方法一樣,只不過注解@PrepareForTest里寫的類不一樣 ,注解里寫的類是需要調用系統方法所在的類。

      六 、無所不能的PowerMock

       (1) 驗證靜態方法:

       PowerMockito.verifyStatic();
       Static.firstStaticMethod(param);

       (2) 擴展驗證:

       PowerMockito.verifyStatic(Mockito.times(2)); //  被調用2次                                Static.thirdStaticMethod(Mockito.anyInt()); // 以任何整數值被調用

       (3) 更多的Mock方法

       http://code.google.com/p/powermock/wiki/MockitoUsage13

      七、PowerMock簡單實現原理

       •  當某個測試方法被注解@PrepareForTest標注以后,在運行測試用例時,會創建一個新的org.powermock.core.classloader.MockClassLoader實例,然后加載該測試用例使用到的類(系統類除外)。

       •   PowerMock會根據你的mock要求,去修改寫在注解@PrepareForTest里的class文件(當前測試類會自動加入注解中),以滿足特殊的mock需求。例如:去除final方法的final標識,在靜態方法的最前面加入自己的虛擬實現等。

       •   如果需要mock的是系統類的final方法和靜態方法,PowerMock不會直接修改系統類的class文件,而是修改調用系統類的class文件,以滿足mock需求。

 

樓主代碼:

package com.ericsson.csp.cst.admin.util;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.core.Response;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.junit.Before;
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;

import com.ericsson.csp.cst.admin.dao.entity.ResponseResult;
import com.ericsson.csp.cst.admin.dao.entity.Syssubp;
import com.ericsson.csp.cst.admin.service.SubscribeService;
import com.ericsson.csp.cst.admin.service.SyssubpService;



@RunWith(PowerMockRunner.class)
public class SubscribeUtilTest{
    
    private Syssubp disp;
    private Syssubp fromdisp;
    private Syssubp nonSubscribedsubp;
    private Syssubp subscribedsubp;
    
    private SubscribeService subscribeService;
    
    private SyssubpService syssubpService;
    
    private SubscribeUtil subscribeUtil;
    
    @Before
    public void init() throws Exception{
        disp=fillInsubp();
        fromdisp=dispsubp();
        nonSubscribedsubp=getNonSubscribedLocalsubp();
        subscribedsubp=getSubscribedLocalsubp();
       
        syssubpService=PowerMockito.mock(SyssubpService.class);
        List<Syssubp> emptyLocalList=new ArrayList<Syssubp>();
        List<Syssubp> nonEmptyLocalList=new ArrayList<Syssubp>();
        nonEmptyLocalList.add(nonSubscribedsubp);
        PowerMockito.doReturn(nonEmptyLocalList).when(syssubpService,"query");
        PowerMockito.doNothing().when(syssubpService,"update",Mockito.any(Syssubp.class));
        PowerMockito.doNothing().when(syssubpService,"save",Mockito.any(Syssubp.class));
        PowerMockito.doNothing().when(syssubpService,"deleteById",Mockito.anyInt());
        
        subscribeService=PowerMockito.mock(SubscribeService.class);
        PowerMockito.doReturn(Response.status(200).type(new String()).entity("a string").build()).when(subscribeService,"subscribe",Mockito.any(Syssubp.class));
        PowerMockito.doReturn(Response.status(200).type(new String()).entity("a string").build()).when(subscribeService,"deletesubp",Mockito.anyInt());
        PowerMockito.when(subscribeService,"getAllsubps").thenReturn(Response.status(200).type(new String()).entity("a string").build());
       
   
    
        subscribeUtil=PowerMockito.spy(new SubscribeUtil());
        subscribeUtil.setSubscribeService(subscribeService);
        subscribeUtil.setsubpService(syssubpService);
    }

    @Test
    @PrepareForTest(SubscribeUtil.class)
    public void testSubscribe() throws Exception {
        
        String skip_createResponseResultByResponse="createResponseResultByResponse";
        String skip_createsubpBydispResponse="createsubpBydispResponse";
        
        ResponseResult result=new ResponseResult();
        result.setStatus(200);
        
        PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
        PowerMockito.doReturn(fromdisp).when(subscribeUtil, skip_createsubpBydispResponse, Mockito.any(ResponseResult.class));

        ResponseResult resp=subscribeUtil.subscribe(nonSubscribedsubp);
        
        
        assertEquals(200, resp.getStatus());
        
    }
    
    @Test
    public void testUpdatesubpLocally() throws JsonGenerationException, JsonMappingException, IOException{
        
        subscribeUtil.updatesubp(nonSubscribedsubp);
    }
    
    @Test
    @PrepareForTest(SubscribeUtil.class)
    public void testUpdatesubpdisply() throws Exception{
        
        ResponseResult result=new ResponseResult();
        result.setStatus(200);
        
        String skip_createResponseResultByResponse="createResponseResultByResponse";
        PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
        String skip_createsubpBydispResponse="createsubpBydispResponse";
        PowerMockito.doReturn(fromdisp).when(subscribeUtil, skip_createsubpBydispResponse, Mockito.any(ResponseResult.class));
        
        subscribeUtil.updatesubp(subscribedsubp);
    }
    
    @Test
    public void testDeletesubpLocally() throws Exception{
        PowerMockito.doReturn(nonSubscribedsubp).when(syssubpService,"queryById",Mockito.anyInt());
        subscribeUtil.deletesubp(100);
    }
    @Test
    @PrepareForTest(SubscribeUtil.class)
    public void testDeletesubpdisply() throws Exception{
        ResponseResult result=new ResponseResult();
        result.setStatus(200);
        
        PowerMockito.doReturn(subscribedsubp).when(syssubpService,"queryById",Mockito.anyInt());
        String skip_createResponseResultByResponse="createResponseResultByResponse";
        PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
      
        subscribeUtil.deletesubp(100);
    }
    
    @Test
    @PrepareForTest({JacksonUtil.class,SubscribeUtil.class})
    public void testSyncdispWhenLocalNonEmpty() throws Exception{
        ResponseResult result=new ResponseResult();
        result.setStatus(200);
        String skip_createResponseResultByResponse="createResponseResultByResponse";
        PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
        
        List<Syssubp> dispList=new ArrayList<Syssubp>();
        dispList.add(fromdisp);
        dispList.add(fromdisp);
        dispList.add(fromdisp);
        
        
        PowerMockito.mockStatic(JacksonUtil.class);
        PowerMockito.when(JacksonUtil.getListByTargetClass(Mockito.anyString(), Mockito.eq(Syssubp.class))).thenReturn(dispList);
        
        subscribeUtil.syncSubcriptionWithdisp();
    }
    
    
    @Test
    @PrepareForTest({JacksonUtil.class,SubscribeUtil.class})
    public void testSyncdispWhenLocalEmpty() throws Exception{
        ResponseResult result=new ResponseResult();
        result.setStatus(200);
        String skip_createResponseResultByResponse="createResponseResultByResponse";
        PowerMockito.doReturn(result).when(subscribeUtil, skip_createResponseResultByResponse, Mockito.any(Response.class),Mockito.any(ResponseResult.class));
        
        List<Syssubp> dispList=new ArrayList<Syssubp>();
        dispList.add(fromdisp);
        dispList.add(fromdisp);
        dispList.add(fromdisp);
        
        
        PowerMockito.mockStatic(JacksonUtil.class);
        PowerMockito.when(JacksonUtil.getListByTargetClass(Mockito.anyString(), Mockito.eq(Syssubp.class))).thenReturn(dispList);
        
        List<Syssubp> emptyLocalList=new ArrayList<Syssubp>();
        PowerMockito.doReturn(emptyLocalList).when(syssubpService,"query");
        
        subscribeUtil.syncSubcriptionWithdisp();
    }

    private Syssubp fillInsubp() {
        Syssubp syssubp=new Syssubp();
        syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
        syssubp.setTopicServiceId("adade");
        syssubp.setEnableTransformation(true);
        syssubp.setUsername("");
        syssubp.setPassword("");
        return syssubp;
    }
    private Syssubp getNonSubscribedLocalsubp() {
        Syssubp syssubp=new Syssubp();
        syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
        syssubp.setTopicServiceId("adade");
        syssubp.setEnableTransformation(true);
        syssubp.setUsername("");
        syssubp.setPassword("");
        syssubp.setApp_name("app");
        syssubp.setCreate_time(new Date());
        syssubp.setId(100);
        return syssubp;
    }
    private Syssubp getSubscribedLocalsubp() {
        Syssubp syssubp=new Syssubp();
        syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
        syssubp.setTopicServiceId("adade");
        syssubp.setEnableTransformation(true);
        syssubp.setUsername("");
        syssubp.setPassword("");
        syssubp.setApp_name("app");
        syssubp.setCreate_time(new Date());
        syssubp.setId(100);
        syssubp.setStatus(true);
        syssubp.setUpdate_time(new Date());
        syssubp.setsubpId(100);
        return syssubp;
    }
    
    private Syssubp dispsubp() {
        Syssubp syssubp=new Syssubp();
        syssubp.setCallbackUrl("http://192.168.3.237:8080/cst-ecall/services/uplink/uplinkService");
        syssubp.setTopicServiceId("adade");
        syssubp.setEnableTransformation(true);
        syssubp.setUsername("");
        syssubp.setPassword("");
        syssubp.setsubpId(100);
        return syssubp;
    }
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM