Java – interaction between JUnit @ rule lifecycle and @ before
I have some JUnit tests using temporaryfolder @ rule They use the temporaryfolder in the @ before method to perform some settings:
@Rule public TemporaryFolder folder = new TemporaryFolder(); @Before public void init() { folder.newFile("my-file.txt"); } @Test public void mytest() { ... }
Most of the time the job is perfect However, when using spring JUnit 4classrunner, I found that in some cases, the init () method was called before the statement in the temporaryfolder instance Therefore, when the folder is used in init (), the temporary folder location is not set (i.e. null), and my files are finally in the working directory instead of / tmp
So in some cases, the rules executed before the @ before method, but I can't establish an explicit pattern I occasionally see some similar problems, and some of my own rules are implemented
Is there any way to ensure that my rule statements are applied before any method is set?
Solution
In JUnit 4.10, blockjunit4classrunner (a superclass of spring junit4classrunner) looks like running rules before any @ before method to construct the statement chain From JUnit 4.10:
protected Statement methodBlock(FrameworkMethod method) { // ... Statement statement= methodInvoker(method,test); statement= possiblyExpectingExceptions(method,test,statement); statement= withPotentialTimeout(method,statement); statement= withBefores(method,statement); statement= withAfters(method,statement); statement= withRules(method,statement); return statement; }
JUnit 4.7 seems to splice the statement chain in different order:
Statement statement= methodInvoker(method,test); statement= possiblyExpectingExceptions(method,statement); statement= withPotentialTimeout(method,statement); statement= withRules(method,statement); statement= withBefores(method,statement); statement= withAfters(method,statement); return statement;
spring-test-3.0. The parent POM of 5 seems to indicate that it depends on JUnit 4.7 I don't know if using updated JUnit will help?