I have a particular class (let's say MyTest
) in my Spring integration tests that is using PowerMock @PrepareForTest
annotation on a Spring component: @PrepareForTest(MyComponent.class)
. This means that PowerMock will load this class with some modifications. The problem is, my @ContextConfiguration
is defined on the superclass which is extended by MyTest
, and the ApplicationContext
is cached between different test classes. Now, if MyTest
is run first, it will have the correct PowerMock version of MyComponent
, but if not - the test will fail since the context will be loaded for another test (without @PrepareForTest).
So what I want to do is to reload my context before MyTest
. I can do that via
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
But what if I also want to reload context after this test is done? So I will have clean MyComponent
again without PowerMock modifications. Is there a way to do both BEFORE_CLASS
and AFTER_CLASS
?
For now I did it with the following hack:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
on MyTest and then
/**
* Stub test to reload ApplicationContext before execution of real test methods of this class.
*/
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
@Test
public void aa() {
}
/**
* Stub test to reload ApplicationContext after execution of real test methods of this class.
*/
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
@Test
public void zz() {
}
I am wondering if there is a prettier way to do that?
As a side question, is it possible to reload only certain bean and not full context?