[譯]Java將Powermock和Mockito搭配進行單元測試

本文為Powermock官方文檔Mockito篇的中文翻譯
原文:https://github.com/powermock/powermock/wiki/Mockito
翻譯:卻把清梅嗅

筆者的Android單元測試相關(guān)系列:

Android單元測試:Mockito使用詳解
Android單元測試:使用本地數(shù)據(jù)測試Retrofit
Android單元測試:測試RxJava的同步及異步操作
Java 將Powermock和Mockito搭配進行單元測試
Android 自動化測試 Espresso篇:簡介&基礎(chǔ)使用
Android 自動化測試 Espresso篇:異步代碼測試

簡介

Powermock提供了基礎(chǔ)的PowerMockito類,你仍然可以通過初始化 mock/object/class 并配置它們的校驗、期望行為、或者其他,以達到通過Mockito配置和驗證你的預(yù)期(例如times(), anyInt())的目的。

所有的操作都需要再Class層級上配置 @RunWith(PowerMockRunner.class) 和 @PrepareForTest 注解

版本支持

image.png

用法


在下面的示例中,我們不對Mockito或PowerMockito API中的方法使用靜態(tài)導(dǎo)入的方式,這便于我們觀察實際代碼是如何被測試的。 但是,我們強烈建議您靜態(tài)導(dǎo)入方法的方式,以提高可讀性。

請注意:Mockito團隊在2.1.0的版本中增加了mock final 類型Class/Methods 的能力。 PowerMock 1.7.0版本之后支持此功能(請使用Mockito 2.8.9進行測試)。 使用PowerMock配置可以啟用該功能。 如果您使用Mockito 2,建議使用Mockito來mock final 類型Class/Methods。

Mock 靜態(tài)方法

下面的代碼將展示如何Mock以及打樁(stub):

1.添加 @PrepareForTest 注解在你的Class層級上。

@PrepareForTest(Static.class) // Static.class contains static methods

2.調(diào)用PowerMockito.mockStatic() 以mock靜態(tài)類(使用PowerMockito.spy(class) 來mock制定的方法).

PowerMockito.mockStatic(Static.class);

3.使用Mockito.when()配置你的期望:

Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);

注意:如果需要模擬java系統(tǒng)/ bootstrap類加載器(在java.lang或java.net等中定義的類)加載的類,則需要調(diào)用[this](Mock-System)方法。

如何驗證行為

想要驗證靜態(tài)方法是否被執(zhí)行完畢,通過以下兩個步驟:

1.首先,調(diào)用 PowerMockito.verifyStatic(Static.class) 來開始驗證行為;
2.然后調(diào)用 Static.class 的靜態(tài)方法進行驗證。

例如:

PowerMockito.verifyStatic(Static.class); // 1
Static.firstStaticMethod(param); // 2

重要:對于每一個方法的驗證,你都需要去調(diào)用 verifyStatic(Static.class)方法。

如何使用參數(shù)匹配器

Mockito的匹配器依然被應(yīng)用在了PowerMock 的mock行為中,下面的代碼講述如何為每個被mock的靜態(tài)方法使用自定義的參數(shù)匹配器:

PowerMockito.verifyStatic(Static.class);
Static.thirdStaticMethod(Mockito.anyInt());

如何驗證方法被調(diào)用的準確次數(shù)

你仍然可以使用Mockito.VerificationMode (e.g Mockito.times(x)) 通過PowerMockito.verifyStatic(Static.class, Mockito.times(2))的方式驗證。

PowerMockito.verifyStatic(Static.class, Mockito.times(1));

如何為返回值為Void類型的靜態(tài)方法拋出異常

如果不是Private修飾的方法,則:

PowerMockito.doThrow(new ArrayStoreException("Mock error")).when(StaticService.class);
StaticService.executeMethod();

注意,您可以對final修飾的 類和方法 執(zhí)行相同的操作:

PowerMockito.doThrow(new ArrayStoreException("Mock error")).when(myFinalMock).myFinalMethod();

對于Private的方法,請使用PowerMockito.when(),比如:

when(tested, "methodToExpect", argument).thenReturn(myReturnValue);

一個完整的案例,講述了如何mock、打樁以及驗證靜態(tài)方法

@RunWith(PowerMockRunner.class)
@PrepareForTest(Static.class)
public class YourTestCase {
    @Test
    public void testMethodThatCallsStaticMethod() {
        // mock all the static methods in a class called "Static"
        PowerMockito.mockStatic(Static.class);
        // use Mockito to set up your expectation
        Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
        Mockito.when(Static.secondStaticMethod()).thenReturn(123);

        // execute your test
        classCallStaticMethodObj.execute();

        // Different from Mockito, always use PowerMockito.verifyStatic(Class) first
        // to start verifying behavior
        PowerMockito.verifyStatic(Static.class, Mockito.times(2));
        // IMPORTANT:  Call the static method you want to verify
        Static.firstStaticMethod(param);


        // IMPORTANT: You need to call verifyStatic(Class) per method verification, 
        // so call verifyStatic(Class) again
        PowerMockito.verifyStatic(Static.class); // default times is once
        // Again call the static method which is being verified 
        Static.secondStaticMethod();

        // Again, remember to call verifyStatic(Class)
        PowerMockito.verifyStatic(Static.class, Mockito.never());
        // And again call the static method. 
        Static.thirdStaticMethod();
    }
}

局部Mock

您可以通過使用PowerMockito.spy來局部mock一個方法,請注意(以下內(nèi)容取自Mockito文檔并同樣適用于PowerMockito):

有時,你并不能使用默認的 when(..)方法為spies打樁,例如:

List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");

//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

如何驗證行為

你只需要使用 Mockito.vertify() 進行默認的校驗:

Mockito.verify(mockObj, times(2)).methodToMock();

如何校驗private的行為

使用 PowerMockito.verifyPrivate(), 比如:

verifyPrivate(tested).invoke("privateMethodName", argument1);

這種方式同樣適用于private 的靜態(tài)方法。

如何對對象的創(chuàng)建進行mock

使用 PowerMockito.whenNew(), 比如:

whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message"));

請注意,您必須準備類creating用于測試的新MyClass實例,而不是MyClass本身。 (翻譯無能,請參考下面的舉例...)

比如說,如果執(zhí)行new MyClass()的類被稱為X,那么你必須執(zhí)行@PrepareForTest(X.class)以使whenNew工作:

@RunWith(PowerMockRunner.class)
@PrepareForTest(X.class)
public class XTest {
        @Test
        public void test() {
                whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message"));

                X x = new X();
                x.y(); // y is the method doing "new MyClass()"
               
                ..
        }
}

如何驗證新對象的實例化

使用 PowerMockito.verifyNew :

verifyNew(MyClass.class).withNoArguments();

如何使用參數(shù)匹配器

Mockito的匹配器依然被應(yīng)用在了PowerMock中:

Mockito.verify(mockObj).methodToMock(Mockito.anyInt());  

譯者注: 以參數(shù)匹配器為例,官方文檔似乎重復(fù)講了兩次,實際上,這兩處分別針對靜態(tài)方法和普通的方法進行了分開的闡述,對于靜態(tài)方法,我們只能通過PowerMock的API進行校驗,但是對于普通的成員方法,使用Mockito提供的API即可。

一個完整講述了Spy的案例:

@RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
@PrepareForTest(PartialMockClass.class)
public class YourTestCase {
    @Test
    public void spyingWithPowerMock() {        
        PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());

        // use Mockito to set up your expectation
        Mockito.when(classUnderTest.methodToMock()).thenReturn(value);

        // execute your test
        classUnderTest.execute();

        // Use Mockito.verify() to verify result
        Mockito.verify(mockObj, times(2)).methodToMock();
    }
}

一個完整講述了對Private方法的局部Mock的案例(PowerMock 1.3.6+版本后提供的支持):

@RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
@PrepareForTest(PartialMockClass.class)
public class YourTestCase {
    @Test
    public void privatePartialMockingWithPowerMock() {        
        PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());

        // use PowerMockito to set up your expectation
        PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");

        // execute your test
        classUnderTest.execute();

        // Use PowerMockito.verify() to verify result
        PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
    }
}

更多信息

想了解更多,請查看GitHub中的source。

另請閱讀Jayway團隊博客中的PowerMockito相關(guān)[博客](http://blog.jayway.com/2009/10/28/untestable-code-with-mockito-and-powermock/)。

關(guān)于譯者

卻把清梅嗅
Github:https://github.com/qingmei2
CSDN:https://blog.csdn.net/mq2553299
簡書:http://www.itdecent.cn/u/df76f81fe3ff

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容