Add support for @javax.inject.Named and Spring's @Qualifier #214

Closed
rliesenfeld opened this Issue Oct 9, 2015 · 2 comments

Projects

None yet

3 participants

@rliesenfeld
Member

Occasionaly, a tested class may have dependencies of different types which, in turn, have some other dependency of a type X, which need to be resolved to different instances of type X.

When using CDI or Spring DI, these X dependencies are usually qualified so they can be properly resolved. CDI's @Named, and Spring's @Qualifier annotations are then used on fields of type X to specify the name of the desired instance.

So, when an injected field is annotated with @Named("name") or @Qualifier("name"), JMockit should look for an @Injectable or @Tested instance of the same type and "name", instead of using the regular searching rules (just the type, or type + injected field name).

@rliesenfeld rliesenfeld self-assigned this Oct 9, 2015
@pith
pith commented Mar 29, 2016

Hi,
I'm using Guice and the support for @Named doesn't seem to work. My tested class has the following field:

@Inject @Named("git")
private FetchService fetchService;

When I mock it using @Injectable:

@Injectable
private FetchService fetchService;

I have the following error:

java.lang.IllegalStateException: Missing @Injectable for field MyTestedService#fetchService, of type org.mycompany.MyTestedService

If I remove the @Named("git") annotation my fetchService is mocked correctly.

@codecounselor

I was working with a colleague recently and we encountered a side effect of this implementation.

The application under test has beans with qualifiers containing dashes. Since this code expects the injectable variable to match the beanId we were in a bit of a pickle.

We worked around it by changing the @Qualifier annotation to @Resource but that may not always be a viable option, and it feels like a hack.

My question is: why not add an attribute to the @Injectable annotation that specifies the bean name in the scenario there are multiple auto-wire candidates?

I haven't dug into the code yet, but if you'll accept a PR to remedy this issue I'd be willing to try and make the contribution myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment