首页 > 解决方案 > 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?我可以在生成的模拟中添加@Alternativewith吗?@Priority(100)

标签: javamockitojax-rsweldjersey-test-framework

解决方案


推荐阅读