From: David S. <da...@sa...> - 2009-10-26 13:52:07
|
Alistair, [I need to try to remember "reply all" and CC junit-devel so that everyone stays involved; I keep forgetting] On Sat, Oct 24, 2009 at 10:02 PM, Alistair Israel <ai...@gm...> wrote: > On Fri, Oct 23, 2009 at 9:25 PM, David Saff <da...@sa...> wrote: > >> I think class-level rules make a lot of sense. Do you think re-using >> the @Rule annotation is better than a new @ClassRule annotation? > > Hi, again, David. > > Finally remembered another reason (in fact, my primary reason) for > reusing @Rule. > > While in some cases, separating a ClassRule from a MethodRule makes > sense (and allows for mixing and matching), in other cases that simply > breaks encapsulation. > > The basic case is an expensive factory object or setup code that's > used to provide a new instance of a resource to each @Test method. The > ClassRule performs "around Class" setup & teardown, but the MethodRule > would use the first to get new instance of the resource (which it uses > for "around @Test" behavior). > > Consider a remote Web service that's used to report test results and > timings to. (I know, it sounds contrived, but I don't want to keep > harping about my own embedded DB + JPA + dependency injection use > case.) > > The setup of the Web service is expensive, and ideally we'd want to > set it up once before all tests, and cleanup after everything's done. > Meanwhile, around each test we want to report start then > success/failure. > > We could separate the two using: > > @ClassRule > public static TestReportingWebService service = new > TestReportingWebService(); > > @Rule > public RemoteTestWatchman watchman = new RemoteTestWatchman(service); > > Or, in my mind it'd be nicer to be able to go: > > @Rule > public static RemoteTestWatchman watchman = new RemoteTestWatchman(); Note that we can get the "one object" behavior with the "two annotations" API: @ClassRule public static RemoteTestWatchman watchman = new RemoteTestWatchman(); @Rule public RemoteTestWatchman methodWatchman = watchman; Is this better? David |