Re: ClassRules

David Saff <[email protected]> Mon, 26 Oct 2009 09:51:56 -0400
Newsgroups gmane.comp.java.junit.devel
Message-ID <[email protected]>
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 <[email protected]> wrote:
> On Fri, Oct 23, 2009 at 9:25 PM, David Saff <[email protected]> wrote:
>
>> I think class-level rules make a lot of sense. =A0Do 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:
>
> =A0 =A0@ClassRule
> =A0 =A0public static TestReportingWebService service =3D new
> TestReportingWebService();
>
> =A0 =A0@Rule
> =A0 =A0public RemoteTestWatchman watchman =3D new RemoteTestWatchman(serv=
ice);
>
> Or, in my mind it'd be nicer to be able to go:
>
> =A0 =A0@Rule
> =A0 =A0public static RemoteTestWatchman watchman =3D new RemoteTestWatchm=
an();

Note that we can get the "one object" behavior with the "two annotations" A=
PI:

@ClassRule
public static RemoteTestWatchman watchman =3D new RemoteTestWatchman();

@Rule public RemoteTestWatchman methodWatchman =3D watchman;

Is this better?

   David

---------------------------------------------------------------------------=
---
Come build with us! The BlackBerry(R) Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay =

ahead of the curve. Join us from November 9 - 12, 2009. Register now!
http://p.sf.net/sfu/devconference