I want to write an JUnit @Rule (version 4.10) to setup some objects (an Entity Manager) and make them available in the test, by “injecting” it into an variable.
Something like this:
public class MyTestClass() {
@Rule
MyEntityManagerInjectRule = new MyEntityManagerInjectRule():
//MyEntityManagerInjectRule "inject" the entity manager
EntityManger em;
@Test...
}
The Problem is that I do not know how to get the current instance of MyTestClass in the MyEntityManagerInjectRule (extends TestRule), because it has only one method.
Statement apply(Statement base, Description description);
Within Description there is only the class MyTestClass but not the instance used for the test.
An alternative would be using org.junit.rules.MethodRule but this is deprecated.
Before and After are not sufficient for this task, because then I would need to copy the code to the tests, and they are more or less deprecated too. (See Block4JClassRunner.withBefores / withAfters).
So my question in how could I access the test class instance without using deprecated stuff.
How about:
Just add the test class instance to the constructor for the
@Rule. Just be careful of the order of assignment.