如何测试实现线程的代码?

时间:2014-12-09 14:28:39

标签: java junit mocking mockito

我希望能够对以下内容进行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。我试图让它抛出异常,例如:

Mockito.doThrow(SQLException.class).when(mockSession).createSQLQuery(any(String.class));

它会在生成的线程中引发异常,但是当我将它作为Junit测试运行时它不会失败。

1 个答案:

答案 0 :(得分:0)

您将要在被测试的类中替换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的直接执行程序,如this SO question and its answers中所示:

@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
}