2017-07-15 113 views
1

我正在使用Java 1.8.0_131,Mockito 2.8.47和PowerMock 1.7.0。我的問題與PowerMock無關,它被髮布到Mockito.when(...)匹配器。Mockito匹配器匹配與仿製藥和供應商的方法

我需要一個解決方案來嘲笑了這種方法,通過我的課下的測試,稱爲:

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。我想返回我的模擬對象。由於泛型不能編譯。不是時候的匹配,所以匹配不工作,則返回null

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

這將編譯但參數在我的:爲了符合我必須寫這樣的類型。我不知道如何編寫匹配我的參數的匹配器,並返回我的模擬對象。你有什麼主意嗎?

非常感謝您 馬庫斯

+0

您可以發佈[MCVE]再現問題: 您可以使用Matcher.<...>any()語法,它指定? – 2017-07-15 07:50:46

+0

對不起,@janos,爲我的後續跟進。我無法在我的項目上工作幾天。今天我用了你的語法和'ArgumentMatcher',我的問題解決了!非常感謝你! –

回答

1

的問題是,編譯器不能推斷出第二個參數的any()的類型。

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

非常坦克,這解決了我的問題! –