我有以下代码:
@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 为其创建一个测试.我写的测试如下:
I would like to create a Test for it using Mockito. I wrote the test as follows:
@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:
I am getting NullPointerException on line:
filter(strategy -> strategy.isApplicable(id))
,它表示策略"列表已初始化但为空.Mohito 有没有办法像 Spring 一样表现得一样?将所有实现接口策略"的实例自动添加到列表中?
, which states that the "strategies" list is initialized but is empty. Is there any way Mohito will behave in the same wasy as Spring? Adding automatically all instances implementing interface "Strategy" to the list?
顺便说一句,我在 Wrapper 类中没有任何设置器,如果可能的话,我想以这种方式保留它.
Btw I do not have any setters in Wrapper class and I would like to leave it in that way if possible.
Mockito 无法知道您想将某些东西放入 List strategies.
Mockito can not know that you want to put somthing in the List strategies.
你应该重新考虑这个并做这样的事情
You should rethink this an do something like this
@InjectMocks
private Wrapper testedObject = new Wrapper ();
private List<Strategy> mockedStrategies;
@Mock
StrategyA strategyA;
@Mock
StrategyB strategyB;
@Before
public void setup() throws Exception {
mockedStrategies = Arrays.asList(strategyA, strategyB);
wrapper.setStrategies(mockedStrategies);
}
这篇关于Mockito - 注入模拟列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!