簡體   English   中英

需要語法來調用 powermock whitebox()

[英]Need syntax to call powermock whitebox()

在我的單元測試中,我試圖使用 Whitebox.invokeMethod 執行私有方法,但我不知道有效的語法。 我想調用它(getExcelMappingJsoDto() 是私有方法)但不確定如何傳遞 arguments

Map<Integer,String> columnMapping = genericExcelCreator.getExcelMappingJsoDto().getSheets().get(0).getColumnMapping();

嘗試這樣的事情,無濟於事:

Map<Integer,String> columnMapping  = Whitebox.invokeMethod(genericExcelCreator, "getExcelMappingJsoDto().getSheets().get(0).getColumnMapping", null);

為了讓 Whitebox 工作,您需要模擬您的GenericExcelCreator class。例如,使用 Mockito 的注釋:

@Mock
private GenericExcelCreator genericExcelCreator;

通常,在開始使用方法之前,我會將方法的返回值分配給一個新變量。 由於我不知道您的返回類型,但請記住 Java 允許方法鏈接,您可以這樣做:

Map<Integer, String> columnMapping = Whitebox.invokeMethod(genericExcelCreator, "getExcelMappingJsoDto").getSheets().get(0).getColumnMapping();

請記住,Whitebox 只需要(方法)名稱,因此在將它傳遞給.invokeMethod時不應添加方括號 ()

此外,Whitebox 的另一個常見用途是更改模擬 class 中私有變量的值。您可以通過以下方式實現:

Whitebox.setInternalState(yourMockedService, "nameOfYourVariable", variableObjectTypeValue);

例如,我可以有一個 class CleanupService和一個可互換的allowCleanup ,我想在false時測試它。 這導致:

Whitebox.setInternalState(cleanupService, "allowCleanup", false); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM