java - WELD-001409:Jersey Test 中由于模拟 bean 的依赖关系不明确
问题描述
我正在尝试在我的控制器测试中创建一个模拟 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
with吗?@Priority(100)
解决方案
推荐阅读
- c++ - 关于封装的 C++ 迭代节点
- api - 贝宝获得客户批准流程不明确
- angularjs - 无法将模态数据输入 angularjs 控制器
- javascript - 应用程序脚本 new Date 和 getTime 在浏览器中的行为不一样
- java - 在大文件中查找重复项和排列
- php - PHP Exec 命令在 apache 重新启动之前不会运行
- sql - SQL开发人员中是否有表对象的锁定机制?
- java - 如何在jsp中从文本字段中获取值到java
- scikit-learn - 标准化缩放是使用 sklearn 应用 PCA 的先决条件吗?
- python - AttributeError:Home 类没有属性“as_view”