2016-11-01 65 views
0

我在我的代碼的不同點以下兩行:匹配器的Mockito不工作

Message<T1> reply = (Message<T1>) template.sendAndReceive(channel1, message); 

Message<T2> reply = (Message<T2>) template.sendAndReceive(channel2, message); 

我做了一些單元測試和測試涵蓋報表。當我嘗試嘲笑的行爲,我定義一些行爲是這樣的:

Mockito.when(template.sendAndReceive(Mockito.any(MessageChannel.class), Matchers.<GenericMessage<T1>>any())).thenReturn(instance1); 

Mockito.when(template.sendAndReceive(Mockito.any(MessageChannel.class), Matchers.<GenericMessage<T2>>any() )).thenReturn(null); 

當我執行單元測試,並做一些調試,第一條語句返回null

你有任何想法的匹配器似乎不工作?它總是需要模擬的最後定義。我使用1.1.10的Mockito

+1

你正在遭受類型擦除。這兩個調用之間唯一不同的是GenericMessage中的'<>'中的泛型 - 它們與運行時Java看起來是一樣的。最好的建議是根據你傳入的對象而不是它們的類型來改變模擬的行爲,然後你會得到你想要的行爲。 –

回答

2

當我執行單元測試,並做一些調試,第一 語句返回空

這是因爲您沒有與thenReturn(..);存根相同的方法調用兩次,最後一個贏得了null


正確的方式來實現自己的目標是提供連續的返回值的列表時,調用該方法將返回:

Mockito.when(template.sendAndReceive(Matchers.any(MessageChannel.class), Matchers.any(GenericMessage.class))) 
    .thenReturn(instance1, null); 

在這種情況下,第一次調用返回的值將爲instance1,並且所有後續調用將返回null。看一個例子here


另一種選擇,因爲阿什利楣建議,將根據參數使template.sendAndReceive返回不同的值:

Mockito.when(template.sendAndReceive(Matchers.same(channel1), Matchers.any(GenericMessage.class))) 
    .thenReturn(instance1); 
Mockito.when(template.sendAndReceive(Matchers.same(channel2), Matchers.any(GenericMessage.class))) 
    .thenReturn(null); 

或者更短,我們可以省略第二行,因爲unstubbed模擬默認返回值方法調用是null

Mockito.when(template.sendAndReceive(Matchers.same(channel1), Matchers.any(GenericMessage.class))) 
    .thenReturn(instance1); 

在這裏,我們假設一些channel1channel2一重新在測試類的範圍內,並被注入到被測對象中(至少從你在問題中提供的代碼片段看起來如此)。

+0

我想過它,但我給了我最後一次嘗試,因爲在我看來,單元測試非常耦合我想測試的代碼 – Deibys

+0

@Deibys,我添加了第二個選項,它不會對任何有關「template.sendAndReceive」的調用完成的順序。 –