Mockito - Injecting a List of mocks

后端 未结 5 787
庸人自扰
庸人自扰 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 00:58

    Annotate it with @Spy instead of @Mock. As Mockito cannot spy on an interface, use a concrete implementation, for example ArrayList. During test setup add the mocks to the List spy. This way you do not need to alter your test subject solely for test purposes.

    @InjectMocks
    private Wrapper testedObject = new Wrapper();
    
    @Spy
    private ArrayList mockedStrategies;
    
    @Mock
    private StrategyA strategyA;
    
    @Mock
    private StrategyB strategyB;
    
    @Before
    public void setup() throws Exception {
        mockedStrategies.add(strategyA);
        mockedStrategies.add(strategyB);
    }
    

提交回复
热议问题