【发布时间】:2017-12-12 09:49:35
【问题描述】:
我有一个简单的测试用例,其中包含一个被监视的模拟对象列表,然后我将其注入到正在测试的类中
@Spy List<ValidateRule> ruleServices = new ArrayList<>();
@Mock
private EvaluateGroupType evaluateGroupType;
@Mock
private ValidateServiceRule validateServiceRule;
@InjectMocks
private ValidateRulesService validateRulesService;
@Before
public void init() throws Exception {
initMocks(this);
}
但是,在 ValidateRulesService 类中,列表被注入到错误的列表中。
List<Integer> demonstrationList = new ArrayList<>();
@Autowired
private List<ValidateRule> ruleServices;
我也尝试将它作为使用构造函数注入来注入,结果是这些值被注入了两次
List<Integer> demonstrationList = new ArrayList<>();
final private List<ValidateRule> ruleServices;
@Autowired
public ValidateRulesService(List<ValidateRule> ruleServices) {
this.ruleServices = ruleServices;
}
我不希望 DemonstationList 在任何一种情况下都有任何值。根据我在@injectmocks 的文档中阅读的内容,它与 rulesService 的名称不同或类型相同。
我在这里做错了什么,还是这是 Mockito 的怪癖?
【问题讨论】:
-
您有什么理由必须监视该列表?模拟和设置还不够吗?
-
@MaciejKowalski 虽然这可能会导致更干净的测试,但它可能仍会导致相同的问题。
-
如果使用 Mock,可以指定要注入的字段的名称
-
如果您模拟列表,则无法向其中添加模拟对象。
-
你可以设置它.. 只是更喧嚣那是真的
标签: java spring spring-boot junit mockito