项目开发的过程中,需要进行单元测试,然而在mock的时候,发现目标类的一个属性是List的:
使用常规的@mock注解方式并没有奏效
那么 这种情况怎么办呢?
解决代码如下:
观察控制台:
成功~
源码贴出:
@RunWith(SpringJUnit4ClassRunner.class)
public class SmartServiceTest {
@InjectMocks
private SmartService smartService;
@Mock
private ASpiServiceImp aSpiServiceImp;
@Spy
private List<TestSpiService> testSpiServiceList = new ArrayList();;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
testSpiServiceList.add(aSpiServiceImp);
}
@Test
public void test1() {
smartService.print();
}
参考资料:https://stackoverflow.com/questions/33302340/how-to-mock-a-autowired-list-of-spring-beans