Mockito:如何正确地模拟Spring服务列表

3
我有以下的Spring服务类,想要使用Mockito进行测试:
@Service
public class ObjectExportService {

    @Autowired
    protected List<SecuredService<? extends SecuredObject>> securedServices;

    public void doStuff() {
        for(int i = 0; i < this.securedServices.size(); i++){
            SecuredService<? extends SecuredObject> securedSrv = this.securedServices.get(i);
            //this access works
        }
        for (SecuredService<? extends SecuredObject> securedSrv : this.securedServices) { //this access does not work
            
        }
    }
}

这是我的测试类,用于那项服务:

@RunWith(MockitoJUnitRunner.class)
public class ObjectExportServiceTest {

    @InjectMocks
    private ObjectExportService objectExportService;

    @Mock
    protected List<SecuredService<? extends SecuredObject>> securedServices;

    @Test
    public void testDoStuff(){
        objectExportService.doStuff();
        Assert.assertTrue(true);
    }
}

当我运行测试时,我得到了一个NullpointerException,但只在for-each循环中出现。
首先,我认为这是一个类似于this线程描述的问题: 我已经模拟了List,并且因此需要模拟iterator()调用。
该线程提供的解决方案对我不起作用,因为我实际上是自动装配List。
1个回答

1

所以我在另一个帖子中偶然发现了this解决方案。只需将@Mock更改为@Spy,问题就得到了解决:

@RunWith(MockitoJUnitRunner.class)
public class ObjectExportServiceTest {

    @InjectMocks
    private ObjectExportService objectExportService;

    @Spy  // <-- change here
    protected List<SecuredService<? extends SecuredObject>> securedServices;

    @Test
    public void testDoStuff(){
        objectExportService.doStuff();
        Assert.assertTrue(true);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接