Can I make Surefire perform expensive setup/teardo

2019-08-12 20:04发布

问题:

I have a series of unit tests that all need to talk to an Apache Zookeeper server. Obviously, if I had a library for mocking server connections (or an easy way to roll my own) that would be optimal, but as far as I can tell none exists at this point, and there's enough moving parts under the hood that I hesitate to try it by hand.

So, our solution so far has been to stand up a dummy server locally, perform the tests, then tear it down at the end. This kind of works, though as far as I can tell there's no easy way to tell Surefire to do something once per entire test run -- at best, I have @BeforeClass and @AfterClass decorations.

The Zookeeper initialization process is turning what should be several-millisecond test runs into several seconds per class, which works out to several minutes for the whole project. If I could set up the tests so that it stands up a server, runs each test, then tears it down, I think I'd see a speedup of at least an order of magnitude.

Is there a simple fix? Am I going about this the wrong way? If there's an existing mock-zookeeper library, or a simple way to roll my own, that's a fine solution too.

回答1:

Sounds like an integration test. Look at 'failsafe' instead of surefire, and do the expensive stuff in the additional lifecycle phases for setup and teardown of integration tests.



回答2:

If using TestNG is an option to you, you could use @BeforeSuite.



回答3:

You might want to check the AbstractSingleSpringContextTests class in Spring. This class loads a Spring context for all the subclasses and only reloads it if the method setDirty() is called.

Is not exactly what you want, but I'm sure you can copy the pattern and use it to start a mock zookeeper server.