Reputation: 3377
I am trying to write an extension for JUnit 5 and was curious if there is a way for me to tap into the mongodb connection that @SpringBootTest
already set up for the test.
So, for example, my extension looks like this:
public class MyExtension implements BeforeTestExecutionCallback {
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
// How do I get at the MongoClient here (or in the class constructor)?
}
}
I can create a new one, of course, but I'd like to reuse the one Spring already set up so the extension won't have to deal with knowing information like URI, auth credentials, etc.
Any ideas?
Upvotes: 0
Views: 265
Reputation: 910
SpringExtension
class provides a method for getting ApplicationContext
associated with the supplied ExtensionContext
.
Then you can get the bean from the ApplicationContext
like this:
public class MyExtension implements BeforeTestExecutionCallback {
@Override
public void beforeTestExecution(ExtensionContext context) throws Exception {
ApplicationContext applicationContext = SpringExtension.getApplicationContext(context);
MongoClient mongoClient = applicationContext.getBean(MongoClient.class);
}
}
Upvotes: 2