我正在使用springockito-annotations 1.0.9
集成测试。
我有以下控制器:
@Autowired
public Controller(
@Qualifier("passwordService ") PasswordService passwordService ,
@Qualifier("validator") Validator validator,
@Qualifier("reportService") ReportService reportService,
DateCalculator dateCalculator,
Accessor accessor){
this.passwordService = passwordService;
this.validator = validator;
this.reportService = reportService;
this.dateCalculator = dateCalculator;
this.accessor = accessor;
}
在测试中,我将使用@ReplaceWithMock注释从上下文中替换 bean。
但不幸的是,它仅适用于没有@Qualifier注释的依赖项。
即,我的测试如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(loader = SpringockitoAnnotatedContextLoader.class, classes = {TestContext.class})
public class ControllerTest {
@Autowired
@ReplaceWithMock
private PasswordService passwordService ;
@Autowired
@ReplaceWithMock
private Validator validator;
@Autowired
@ReplaceWithMock
private ReportService reportService;
@Autowired
@ReplaceWithMock
private DateCalculator dateCalculator;
@Autowired
@ReplaceWithMock
private Accessor accessor;
@Autowired
private Controller controller;
}
在初始化上下文后的最后一种情况下,只有DateCalculator 和 Accessor bean 正确替换为所需的模拟,但另一个 bean 自动装配为来自 main context 的普通 bean。
调试后我发现QualifierAnnotationAutowireCandidateResolver无法正确识别 bean。在以下从229开始的行中:
RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();
AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
Spring 试图从mocked dependency中提取限定符,但它是空的。
很高兴知道如何用@Qualifier 正确替换依赖项来模拟对象。