我正在尝试在控制器测试中创建一个模拟bean。该测试由于含糊不清而失败,存在2个具有相同限定符的bean。
测试代码:
public class HelloControllerTest extends JerseyTest {
@Mock
private HelperService helperService;
@InjectMocks
private GreetingsService greetingsService;
@Override
protected Application configure() {
MockitoAnnotations.initMocks(this);
return new ResourceConfig(HelloController.class)
.register(new AbstractBinder() {
@Override
protected void configure() {
bind(helperService).to(HelperService.class);
}
});
}
@Test
public void testHello(){
String mockResponse = "Hello from mocked helper service!";
Mockito.when(helperService.hello()).thenReturn(mockResponse);
String entity = target("/hello").request().get(String.class);
Assert.assertEquals("Wrong response", mockResponse, entity);
}
}
源代码:
@Path("/")
@Produces("application/text")
public class HelloController {
private final GreetingsService greetingsService;
@Inject
public HelloController(GreetingsService greetingsService) {
this.greetingsService = greetingsService;
}
@GET
@Path("hello")
public Response hello(){
return Response.ok(greetingsService.hello()).build();
}
}
@ApplicationScoped
public class GreetingsService {
private final HelperService helperService;
@Inject
public GreetingsService(HelperService helperService){
this.helperService = helperService;
}
public String hello(){
return helperService.hello();
}
}
public class HelperService {
public String hello(){
return "Hello from helper service!";
}
}
@ApplicationScoped
public class HelperServiceProducer {
@Produces
public HelperService createHelperService(){
return new HelperService();
}
}
测试失败,但有以下例外:
org.jboss.weld.exceptions.DeploymentException: WELD-001409: Ambiguous dependencies for type HelperService with qualifiers @Default
at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject public example.services.GreetingsService(HelperService)
at example.services.GreetingsService.<init>(GreetingsService.java:0)
Possible dependencies:
- org.glassfish.jersey.inject.cdi.se.bean.InstanceBean@1929425f,
- Producer Method [HelperService] with qualifiers [@Any @Default] declared as [[BackedAnnotatedMethod] @Produces public example.utils.HelperServiceProducer.createHelperService()]
代码源位于https://github.com/maximkir/study-weld
问题是如何将创建的模拟bean标记为所需的注入bean?我可以将@Alternative
和@Priority(100)
添加到生成的模拟中吗?