tomakehurst/wiremock — pull request #11 by pimterry (2012-12-29 00:37:04+00:00)
Title: @ClassRule support in WireMockRule

As of version 4.9, JUnit has `@ClassRule`, in addition to `@Rule`, allowing you to create rules that run once per class. WireMockStaticRule basically simulates this at the moment, but requires you to manually add an `@AfterClass` method that stops the server, since it can't understand the actual test class context to know when all tests are completed. WireMockStaticRule also has to do that start and WireMock.configure() in its constructor, rather than on application, which seemed a bit nasty.

With this patch, you can instead just write:

@ClassRule
@Rule
public static WireMockRule rule = new WireMockRule();

And it'll start and stop a wiremock once only per test class, and reset the wiremock between tests. In addition the current main use case:

@Rule
public WireMockRule rule = new WireMockRule();

Still works as it does now; creating, starting & stopping a fresh wiremock for each test.

Hopefully all fairly straight-forward, and this made my life a little tidier, so I thought I'd push it back.

The tests are a little ropey, in that they're really only checking it doesn't explode, not that it's only using one instance or that it's correctly stopping the wiremock, but I can't think of any sensible way of doing otherwise. Suggestions welcomed! Meanwhile I've also slightly tidied up that test class into inner classes, to make the rules independent between tests.

Another note: WireMockRule now implements TestRule, in addition to MethodRule. These are both basically the same, but MethodRule is deprecated (replaced by TestRule), and rules are required to implement TestRule instead if they want to support, for example, @ClassRule. If you're happy dropping support for rules in JUnit < 4.9 you can trivially switch over to just using the TestRule interface, but for now I've left both in.