我有下面的代码:
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
被嘲笑。