簡體   English   中英

Mockito匹配器與泛型和供應商匹配方法

[英]Mockito matcher to match a method with generics and a supplier

我使用的是Java 1.8.0_131,Mockito 2.8.47和PowerMock 1.7.0。 我的問題與PowerMock無關,它被發布到Mockito.when(...)匹配器。

我需要一個模擬這個方法的解決方案,這個方法由我的測試類調用:

public static <T extends Serializable> PersistenceController<T> createController(
    final Class<? extends Serializable> clazz,
    final Supplier<T> constructor) { … }

從被測試的類中調用該方法,如下所示:

PersistenceController<EventRepository> eventController =
    PersistenceManager.createController(Event.class, EventRepository::new);

對於測試,我首先創建我的模擬對象,在調用上面的方法時應該返回:

final PersistenceController<EventRepository> controllerMock =
    mock(PersistenceController.class);

那很簡單。 問題是方法參數的匹配器,因為該方法將泛型與供應商結合使用作為參數。 以下代碼按預期編譯並返回null:

when(PersistenceManager.createController(any(), any()))
    .thenReturn(null);

當然,我不想返回null。 我想要返回我的模擬對象。 由於泛型,這不能編譯。 為了符合類型,我必須寫這樣的東西:

when(PersistenceManager.createController(Event.class, EventRepository::new))
    .thenReturn(controllerMock);

這編譯但我的when中的參數不是匹配器,因此匹配不起作用並返回null。 我不知道如何編寫匹配我的參數的匹配器並返回我的模擬對象。 你有什么主意嗎?

非常感謝Marcus

問題是編譯器無法推斷第二個參數的any()的類型。 您可以使用Matcher.<...>any()指定它Matcher.<...>any()語法:

when(PersistenceManager.createController(
    any(), Matchers.<Supplier<EventRepository>>any())
).thenReturn(controllerMock);

如果您使用2的Mockito(其中Matchers已過時),然后使用ArgumentMatchers代替:

when(PersistenceManager.createController(
    any(), ArgumentMatchers.<Supplier<EventRepository>>any())
).thenReturn(controllerMock);

暫無
暫無

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

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