Mockito - Injecting a List of mocks

后端 未结 5 806
庸人自扰
庸人自扰 2020-12-31 00:50

I have the following code:

@Component 
public class Wrapper
{ 
    @Resource 
    private List strategies;

    public String getName(String          


        
5条回答
  •  感情败类
    2020-12-31 01:11

    Why not just mock out your call to toStream()?

    @InjectMocks
    private Wrapper testedObject = new Wrapper();
    
    private List mockedStrategies;
    
    @Mock
    StrategyA strategyA;
    
    @Mock
    StrategyB strategyB;
    
    @Before
    public void setup() {
        when(strategies.stream()).thenReturn(Stream.of(strategyA, strategyB));
    }
    

    To me this is far more elegant as it doesn't require you to add a helper method that is only relevant to testing to your code.

提交回复
热议问题