【发布时间】:2017-02-20 17:44:08
【问题描述】:
我有以下代码:
@Component
public class Wrapper
{
@Resource
private List<Strategy> strategies;
public String getName(String id)
{
// the revelant part of this statement is that I would like to iterate over "strategies"
return strategies.stream()
.filter(strategy -> strategy.isApplicable(id))
.findFirst().get().getAmount(id);
}
}
@Component
public class StrategyA implements Strategy{...}
@Component
public class StrategyB implements Strategy{...}
我想使用 Mockito 为其创建一个测试。 我写的测试如下:
@InjectMocks
private Wrapper testedObject = new Wrapper ();
// I was hoping that this list will contain both strategies: strategyA and strategyB
@Mock
private List<Strategy> strategies;
@Mock
StrategyA strategyA;
@Mock
StrategyB strategyB;
@Test
public void shouldReturnNameForGivenId()
{ // irrevelant code...
//when
testedObject.getName(ID);
}
我在线收到 NullPointerException:
filter(strategy -> strategy.isApplicable(id))
,它表示“策略”列表已初始化但为空。 Mohito 有没有办法像 Spring 一样表现得一样?将所有实现接口“策略”的实例自动添加到列表中?
顺便说一句,我在 Wrapper 类中没有任何设置器,如果可能的话,我想以这种方式保留它。
【问题讨论】:
标签: java spring junit dependency-injection mockito