我希望能够对以下内容进行 junit 测试:
private ExecutorService executor = Executors.newSingleThreadExecutor();
public void foo() {
final EntityManagerFactory entityManagerFactory =
entityManager.getEntityManagerFactory();
executor.execute(new Runnable() {
@Override
public void run() {
EntityManager entityManager =
entityManagerFactory.createEntityManager();
Session session = (Session) entityManager.getDelegate();
try {
SQLQuery query =
session.createSQLQuery("SELECT * from foo_function()");
} catch (HibernateException exception) {
LOGGER.error("Exception: " + exception);
}
}
});
}
我正在使用莫克托。我试图让它抛出异常,例如:
Mockito.doThrow(SQLException.class).when(mockSession).createSQLQuery(any(String.class));
它会在生成的线程中引发异常,但当我将其作为 Junit 测试运行时,它不会失败。
您需要
替换被测类中的 Executor 或 ExecutorService:
public class YourClass {
private Executor executorService = Executor.newSingleThreadExecutor();
public YourClass() {}
/** package-visible for testing */
YourClass(Executor executor) {
/* ... */
}
public void foo() { /* ... */ }
}
。或者只是在你正在测试的方法中:
public class YourClass {
public void foo() {
foo(executorService);
}
/** package-visible for testing */
void foo(Executor executor) {
/* ... */
}
}
之后,您可以使用手动或基于 Guava 的直接执行器,如这个 SO 问题及其答案:
@Test public void fooShouldHandlException() {
// ...
systemUnderTest.foo(new Executor() {
@Override public void execute(Runnable r) { r.run(); }
});
// ...
}
或者将其替换为 Mockito 模拟,以在运行 Runnable 之前和之后进行测试:
@Test public void fooShouldHandlException() {
Executor mockExecutor = Mockito.mock(Executor.class);
ArgumentCaptor<Runnable> runnableCaptor =
ArgumentCaptor.forClass(Runnable.class);
systemUnderTest.foo(mockExecutor);
// assert "before Runnable is run" state, if applicable
verify(mockExecutor).execute(runnableCaptor.capture());
runnableCaptor.getValue().run();
// assert "after Runnable is run" state
}