[英]In jmockit, how can I mock a void method to throw an Exception on the first call and not to on subsequent calls?
[英]How can I mock a void method to throw an exception?
我有這樣的結構:
public class CacheWrapper {
private Map<Object, Object> innerMap;
public CacheWrapper() {
//initialize the innerMap with an instance for an in-memory cache
//that works on external server
//current implementation is not relevant for the problem
innerMap = ...;
}
public void putInSharedMemory(Object key, Object value) {
innerMap.put(key, value);
}
public Object getFromSharedMemory(Object key) {
return innerMap.get(key);
}
}
我的客戶端類(你可以說它看起來像這樣):
public class SomeClient {
//Logger here, for exception handling
Logger log = ...;
private CacheWrapper cacheWrapper;
//getter and setter for cacheWrapper...
public Entity getEntity(String param) {
Entity someEntity = null;
try {
try {
entity = cacheWrapper.getFromSharedMemory(param);
} catch (Exception e) {
//probably connection failure occurred here
log.warn("There was a problem when getting from in-memory " + param + " key.", e);
}
if (entity == null) {
entity = ...; //retrieve it from database
//store in in-memory cache
try {
cacheWrapper.put(param, entity);
} catch (Exception e) {
//probably connection failure occurred here
log.warn("There was a problem when putting in in-memory " + param + " key.", e);
}
}
} catch (Exception e) {
logger.error(".......", e);
}
return entity;
}
}
我正在為SomeClient#getEntity
方法創建單元測試,並且必須涵蓋所有方案。 例如,我需要介紹cacheWrapper
拋出異常的cacheWrapper
。 我正在遵循的方法是為CacheWrapper
類創建一個模擬,使CacheWrapper
類上的方法拋出RuntimeException
,在SomeClient
的實例中設置這個mock並測試Someclient#getEntity
。 問題是在嘗試模擬putInSharedMemory
方法時因為void
。 我已經嘗試了很多方法來做到這一點,但沒有一個工作。 該項目依賴於PowerMock和EasyMock 。
以下是我的嘗試:
EasyMock.<Void>expect
。 這引發了編譯器錯誤。 試圖存根CacheWrapper#putInSharedMemory
。 沒有用,因為這個錯誤消息引發了異常:
java.lang.AssertionError:意外的方法調用putInSharedMemory(“foo”,com.company.domain.Entity @ 609fc98)
為項目添加了Mockito依賴項以利用PowerMockito
類的功能。 但這引發了一個例外,因為它沒有與EasyMock集成。 這是一個例外:
java.lang.ClassCastException:org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl無法強制轉換為org.powermock.api.mockito.internal.invocationcontrol.MockitoMethodInvocationControl
以下是此單元測試示例的代碼:
@Test
public void getEntityWithCacheWrapperException() {
CacheWrapper cacheWrapper = mockThrowsException();
SomeClient someClient = new SomeClient();
someClient.setCacheWrapper(cacheWrapper);
Entity entity = someClient.getEntity();
//here.....................^
//cacheWrapper.putInSharedMemory should throw an exception
//start asserting here...
}
//...
public CacheWrapper mockThrowsException() {
CacheWrapper cacheWrapper = PowerMock.createMock(CacheWrapper.class);
//mocking getFromSharedMemory method
//this works like a charm
EasyMock.expect(cacheWrapper.getFromSharedMemory(EasyMock.anyObject()))
.andThrow(new RuntimeException("This is an intentional Exception")).anyTimes();
//mocking putInSharedMemory method
//the pieces of code here were not executed at the same time
//instead they were commented and choose one approach after another
//attempt 1: compiler exception: <Void> is not applicable for <void>
EasyMock.<Void>expect(cacheWrapper.putInSharedMemory(EasyMock.anyObject(), EasyMock.anyObject()))
.andThrow(new RuntimeException("This is an intentional Exception")).anyTimes();
//attempt 2: stubbing the method
//exception when executing the test:
//Unexpected method call putInSharedMemory("foo", com.company.domain.Entity@609fc98)
Method method = PowerMock.method(CacheWrapper.class, "putInSharedMemory", Object.class, Object.class);
PowerMock.stub(method).toThrow(new RuntimeException("Exception on purpose."));
//attempt 3: added dependency to Mockito integrated to PowerMock
//bad idea: the mock created by PowerMock.createMock() belongs to EasyMock, not to Mockito
//so it breaks when performing the when method
//exception:
//java.lang.ClassCastException: org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl
//cannot be cast to org.powermock.api.mockito.internal.invocationcontrol.MockitoMethodInvocationControl
//at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:54)
PowerMockito.doThrow(new RuntimeException("Exception on purpose."))
.when(cacheWrapper).putInSharedMemory(EasyMock.anyObject(), EasyMock.anyObject());
PowerMock.replay(cacheWrapper);
return cacheWrapper;
}
我無法更改CacheWrapper
的實現,因為它來自第三方庫。 另外,我不能使用EasyMock#getLastCall
因為我正在對SomeClient#getEntity
進行測試。
我怎么能克服這個?
由於您的課程都不是最終的,您可以使用“純粹的模擬”,而無需使用PowerMockito:
final CacheWrapper wrapper = Mockito.spy(new CacheWrapper());
Mockito.doThrow(something)
.when(wrapper).putInSharedMemory(Matchers.any(), Matchers.any());
請注意,存根的“方法參數”實際上是參數匹配器; 你可以放置特定的值(如果沒有被特定方法“包圍”,它將調用.equals()
)。 因此,您可以針對不同的參數不同地指導存根的行為。
此外,不需要任何與Mockito的.replay()
,這是非常好的!
最后,請注意您也可以執行doCallRealMethod()
。 在那之后,這取決於你的場景......
(注意:maven上的最后一個mockito版本是1.10.17 FWIW)
你在使用EasyMock還是Mockito? 兩者都是不同的框架。
PowerMockito是可以與這兩個框架一起使用的超集(或更多補充)。 PowerMockito允許您執行Mockito或EasyMock不能執行的操作。
試試這個用於存根void方法來拋出異常:
EasyMock的:
// First make the actual call to the void method.
cacheWrapper.putInSharedMemory("key", "value");
EasyMock.expectLastCall().andThrow(new RuntimeException());
校驗:
的Mockito:
// Create a CacheWrapper spy and stub its method to throw an exception.
// Syntax for stubbing a spy's method is different from stubbing a mock's method (check Mockito's docs).
CacheWrapper spyCw = spy(new CacheWrapper());
Mockito.doThrow(new RuntimeException())
.when(spyCw)
.putInSharedMemory(Matchers.any(), Matchers.any());
SomeClient sc = new SomeClient();
sc.setCacheWrapper(spyCw);
// This will call spyCw#putInSharedMemory that will throw an exception.
sc.getEntity("key");
使用expectLastCall
,如:
cacheWrapper.putInSharedMemory(EasyMock.anyObject(), EasyMock.anyObject())
EasyMock.expectLastCall().andThrow(new RuntimeException("This is an intentional Exception")).anyTimes();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.