'How to create single object in extension and injection
I have the following class
@ExtendWith({SomeExtension.class})
public class Test{
@Inject
private User user
//some code
}
The code of SomeExtension class
public class SomeExtension implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback, AfterEachCallback {
@Inject
private User user;
//some code
}
Is it possible for each class that implements the SomeExtension extension to create only one instance of the User class, or in other words, is it possible for the User class variable from the SomeExtension extension and the User class variable from the Test class to refer to the same object? @Singleton is not suitable for me, because it create single object for all classes
Solution 1:[1]
In order to access inject a dedicated object instance not being a singleton from Guice into a Junit extension you can implement these three steps:
Guice JUnit support
For adding support of Guice to JUnit you can use the GuiceExtension. This enables injection at any state of you unit test but not for any other test extension, as explained within the references docs.
Accessing Guice from extension
With following code snippet you can access the Guice injector, created by the GuiceExtension, within your own extension:
private static Injector getInjector(ExtensionContext context) {
final Namespace GUICE_EXT_NAMESPACE = Namespace.create("name", "falgout", "jeffrey", "testing", "junit", "guice");
if (!context.getElement().isPresent()) {
return null;
}
AnnotatedElement element = context.getElement().get();
Store store = context.getStore(GUICE_EXT_NAMESPACE);
Injector injector = store.get(element, Injector.class);
if (injector == null) {
//traverse to parent context (recursively!)
if (context.getParent().isPresent()) {
return getInjector(context.getParent().get());
}
return null;
}
return injector;
}
Inside the extension you simple provide the ExtensionContext like:
@Override
public void afterEach(ExtensionContext context) throws Exception {
Injector injector = getInjector(context);
...
Injecting dedicated type instance
Without defining a type instance as @Singleton Guice will create one new object on each access with @Inject or Injector.getInstance(). To retrieve a particular object instance of your class User you can use a binding annotation like @Named as documented in Guice Binding Annotations:
@Provides
@Named("MyUser")
public User myUser() {
return new MyUserImpl();
}
and access it with
@Provides
@Named("MyUser")
private User user();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
