From: Alistair I. <ai...@gm...> - 2009-10-19 10:06:14
|
Hi, list. Hope I'm not overstepping by just barging in like this. Anyway, I'm one of those early adopters of JUnit 4.7's new @Rules. As I use them more and more I've also been seeing the usefulness of class-level rules more and more. A concrete use case of mine is initializing a JPA (Hibernate) persistence context backed by an embedded Derby database, then using DbUnit to load fixtures and populate the database. Using JUnit 4.7, I'm able to accomplish the above using a single MethodRule that does everything for every test method. The performance drawback should be obvious—we need to initialize Derby DB, set up Hibernate JPA, scan for annotated classes and create the tables to match the entities for _every test method_. I've taken the liberty of forking, branching, and committing some changes to JUnit that allow for class-level rules. It's up on GitHub, and the meat of the changes are here: http://github.com/AlistairIsrael/junit/commit/79ef5a7e1d7fa144cc81c9414f4791aaea8b3d75 The gist of it: * Created the ClassRule interface that declares the apply(Statement, TestClass) method. * Modified ParentRunner to scan for fields that are a) annotated with @Rule, b) static, and c) implement ClassRule. * If any are found, then apply them in the order found, allowing them to append to the head of the Statement chain. * Modified BlockJUnit4ClassRunner so validation treats ClassRules appropriately, and only apply MethodRules in methodBlock() I've also added a ClassRulesTest to AllTests to verify the above. Using a local-build, I successfully refactored my specific use-case and split the compound rule into a separate ClassRule (set up Derby and Hibernate) and a MethodRule (load DbUnit fixtures). Not only are the resulting tests more efficient, this strategy lets each Rule to be used independently, even allows for mixing and matching of different database, JPA or fixtures providers. I have a few more ideas on where this can go, but I'd like to get some feedback first if this is something that's welcome or if you guys have another direction you think we should take. Thanks, - alistair -- http://alistairisrael.wordpress.com |