gpt4 book ai didi

java - 我如何模拟一个 void 方法来抛出异常?

转载 作者:搜寻专家 更新时间:2023-10-30 21:42:22 25 4
gpt4 key购买 nike

我有这样的结构:

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 上创建方法类扔RuntimeException , 在 SomeClient 的实例中设置此模拟和测试Someclient#getEntity .问题是在尝试模拟 putInSharedMemory 时方法因为是void .我已经尝试了很多方法来做到这一点,但没有一种有效。 该项目依赖于 PowerMock 和 EasyMock

这是我的尝试:

  1. 使用 EasyMock.<Void>expect .这引发了编译器错误。
  2. 试图 stub CacheWrapper#putInSharedMemory .没有工作,因为引发了异常并显示此错误消息:

    java.lang.AssertionError: Unexpected method call putInSharedMemory("foo", com.company.domain.Entity@609fc98)

  3. 向项目添加 Mockito 依赖项以利用 PowerMockito 的功能类(class)。但这引发了一个异常,因为它没有与 EasyMock 集成。这是引发的异常:

    java.lang.ClassCastException: org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl cannot be cast to 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 上执行测试.

我怎样才能克服这个问题?

最佳答案

因为你的类(class)都不是最终的,你可以使用“pure mockito”而不求助于 PowerMockito:

final CacheWrapper wrapper = Mockito.spy(new CacheWrapper());

Mockito.doThrow(something)
.when(wrapper).putInSharedMemory(Matchers.any(), Matchers.any());

请注意 stub 的“方法参数”实际上是参数匹配器;您可以放置​​特定值(如果没有被特定方法“包围”,它将调用 .equals())。因此,您可以针对不同的参数以不同方式引导 stub 的行为。

此外,Mockito 不需要任何类型的 .replay(),这非常好!

最后,请注意您也可以doCallRealMethod()。之后就看你的场景了……

(注意:maven 上可用的最后一个 mockito 版本是 1.10.17 FWIW)

关于java - 我如何模拟一个 void 方法来抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com