Reputation: 189
I have custom TestExecutionListener:
public class CustomExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
// some code ...
}
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
// some code ...
}
}
In my test class I configure it as follows:
@TestExecutionListeners({
DirtiesContextTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
CustomExecutionListener.class
})
class MyTestClass {
private static ApplicationContext appContext;
@BeforeAll
static void init() {
appContext = new AnnotationConfigWebApplicationContext();
// register some configs for context here
}
@Test
void test() {
}
}
And CustomExecutionListener
doesn't work - in debugger I even don't go there. I suppose that may be problem in the way I create ApplicationContext
: may be TestContext
encapsulates not my appContext
? (I don't properly understand how TestContext
is creating. May be someone could explain?) But even then it should at least go to the beforeTestMethod
in lestener? Or not?
And second question: if it really encapsulates not my appContext
how I can fix that? I. e. set my appContext
to testContext.getApplicationContext()
? I need to be able to extract beans from my appContext
like testContext.getApplicationContext().getBean(...)
.
Upvotes: 0
Views: 1015
Reputation: 31267
For starters, the TestExecutionListener
is only supported if you are using the Spring TestContext Framework (TCF).
Since you are using JUnit Jupiter (a.k.a., JUnit 5), you need to annotate your test class with @ExtendWith(SpringExtension.class)
or alternatively with @SpringJUnitConfig
or @SpringJUnitWebConfig
.
Also, you should not create your ApplicationContext
programmatically. Rather, you let the TCF do that for you -- for example, by specifying declaratively which configuration classes to use via @ContextConfiguration
, @SpringJUnitConfig
, or @SpringJUnitWebConfig
.
In general, I recommend you read the Testing chapter of the Spring Reference Manual, and if that doesn't help enough you can certainly find tutorials for "integration testing with Spring" online.
Regards,
Sam (author of the Spring TestContext Framework)
Upvotes: 3
Reputation: 1750
Did you try @Before
which is not required static methods??
private static ApplicationContext appContext;
@Before
public void init() {
if(appContext == null) {
appContext = new AnnotationConfigWebApplicationContext();
// register some configs for context here
}
}
Upvotes: 0