我有以下代码:
public final class JoinableTaskPool<T> extends ABC {
public Future<T> submit(final Callable<T> task) {
executorService.submit(new Runnable() {
public void run() {
try {
final Future<T> result = service.take();
try {
handler.processResult(result);
} catch (final Throwable t) {
throw new SearchException("Task has an error", t);
}
} catch (InterruptedException e) {
throw new SearchException("Task has an error", e);
}
}
}
}
}
我正在尝试为此方法编写单元测试。方法如下:
@RunWith(MockitoJUnitRunner.class)
public class TestJoinableTaskPool<T> {
private JoinableTaskPool<T> pool;
@Before
public void setUp() {
pool = new JoinableTaskPool<T>(1);
}
@After
public void tearDown() {
pool.shutdown();
}
@Test
public void testSubmit() throws Exception{
Callable task = (Callable<T>) () -> null;
Future<T> result = new FutureTask<T>(task);
Mockito.when(pool.getCompService().take())
.thenReturn(result);
Mockito.when(pool.getFinishHandler().processResult(result))
.thenThrow(RuntimeException.class);
pool.submit(task);
}
}
我在下面一行收到编译错误:
reason: no instance(s) of type variable(s) T exist so that void conforms to T
Mockito.when(pool.getFinishHandler().processResult(result))
.thenThrow(RuntimeException.class);
我们如何解决这个问题?我尝试将 T
替换为 String
或任何其他类,但问题仍然存在。将 any()
作为参数传递给 processResult
现在也可以正常工作,我希望该方法调用抛出一个断言的异常。
如有任何帮助,我们将不胜感激。
最佳答案
您的测试类是通用的。您期望它的具体类型来自哪里?该消息已经告诉它:“no instance(s) of type variable(s) T exist
”。
如果我从 TestJoinableTaskPool
中删除类型参数并替换所有 <T>
具有具体类型,例如Object
,Mockito抛出异常:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles); Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods *cannot* be stubbed/verified. Mocking methods declared on non-public parent classes is not supported. 2. inside when() you don't call method on mock but on some other object.
这是可以理解的,因为 .processResult(result)
在 Handler
上调用但没有Handler
mock 。
关于java - Future<T> 类型的 Mockito Mock 方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62335532/