0

我有许多带有许多测试的 junit 4 测试类。其中许多测试需要 DataSource 来访问数据库。

为了加快测试速度,我想为所有测试类共享一个数据源。这将避免连接成本。

所以我把数据源放在一个静态变量中。

但是我还没有找到关闭它的方法!

使用@Rule + TestWatcher,我们可以在单个测试之前和之后执行代码......使用@ClassRule + TestWatcher,我们可以在单个测试类之前和之后执行代码......

但是在执行完所有执行的测试类之后如何执行代码呢?

测试套件似乎不合适,因为我正在执行所有、一个或任何 junits 测试的子集。

任何想法?

4

2 回答 2

0

You can use ClassRule

public static class GlobalDataSource extends ExternalResource
  private int count = 0;
  private DataSource dataSource;

  private GlobalDataSource() {};

  public static final GlobalDataSource INSTANCE = new GlobalDataSource();

  public DataSource get() {
    if (dataSource == null) {
      throw new IllegalStateException();
    }
    return dataSource;
  }

  @Override
  protected void before() throws Throwable {
    if (count++ == 0) {
      dataSource = createDataSource();
    }
  }

  @Override
  protected void after() {
    if (--count == 0) {
      try {
        destroyDataSource(dataSource);
      } finally {
        dataSource = null;
      }
    }
  };
};

In your tests:

@RunWith(JUnit4.class)
public class FooTest {
  @ClassRule public static GlobalDataSource source = GlobalDataSource.INSTANCE;

  @Test
  public void readDataSource() {
    ...
  }
}

Then create a suite:

@RunWith(Suite.class)
@SuiteClasses(FooTest.class, BarTest.class ...)
public class AllTests {
  @ClassRule public static GlobalDataSource source = GlobalDataSource.INSTANCE;
}

Be aware that global state in tests can be just as problematic as global state in code. A failure in one test could lead other tests to fail.

于 2013-02-01T06:51:01.523 回答
0

在这种情况下,安装JVM 关闭挂钩并不会显得太难看。

比仅在对象被垃圾回收时调用的 finalize() 方法可靠得多。

如果进程中断,则不会调用,但在这种情况下,无论如何都无能为力。所以我没有发现主要的缺点。

谢谢。

于 2013-02-01T13:35:40.223 回答