虽然如果没有自定义 Runner,您无法完全满足您的要求,但您可以确保在@Before
方法中创建的所有数据都使用规则提交:
public class LocalDatabase extends ExternalResource {
private DataSource dataSource;
@Override
protected void before() {
dataSource = createLocalDatabase();
}
@Override
protected void after() {
try {
destoyLocalDatabase(dataSource);
} finally {
dataSource = null;
}
}
public void run(Callback callback) {
if (dataSource == null) {
throw new IllegalStateException("No DataSource");
}
Collection con = null;
try {
con = ds.getConnection(DB_USERNAME, PASSWORD);
callback.execute(con);
con.commit();
} finally {
if (con != null) con.close();
}
}
您可以将其作为基类中的规则:
public DatabaseTest {
@Rule
public LocalDatabase final localDatabase = new LocalDatabase();
}
并且可以@Before
在任何子类的方法中使用它
public UserDaoTest extends DatabaseTest {
@Before
public void populateInitialData() {
localDatabase.run(new Callback() {
@Override
public void execute(Connection con) {
...
}
});
}
...
}