Mockito-注入模拟列表 [英] Mockito - Injecting a List of mocks

查看:116
本文介绍了Mockito-注入模拟列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

@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不知道您想将东西放入列表策略.

Mockito can not know that you want to put somthing in the List strategies.

您应该重新考虑这样做

@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-注入模拟列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆