Mockito。正在创建的内部对象中的方法调用计数

时间:2018-08-19 14:49:07

标签: java junit automated-tests mockito

我有一些类和方法:

class Verificator {

   private Dao dao;
   private VerifyConsts verifyConsts;

   @Autowired
   public Verificator(Dao dao, VerifyConstants verifyConsts) {
        this.dao = dao;
        this.verifyConsts = verifyConsts;
   }

   public List<Pair<Products, Problem>> verify(final List<Product> links) {
     //do smth
     return new ProductVerifyLink().verifyLinks(links, verifyConstants.getForisInstanceZoneId(), dao.getDate());
   }

}

我还有另一堂课:

public class ProductVerifyLink {

    public List<Pair<Products, Problem>> verifyLinks(List<Product> links,
            final ZoneId zone,
            final Timestamp date
    ) throws Exception {
        //do smth
        List<Pair<Product, Problem>> res = verification(ImmutableList.of(links), zone);
        return res.isEmpty() ? null : res;
    }

    private List<Pair<Product, Problem>> verification(List<Product> links, ZoneId zone) {
      //do smth
    }
    //other methods
}

我创建了测试:

    @Test
    public void calcTest() throws Exception {   
        final DAO dao = mock(DAO.class);
        final VerifyConstants verifyConsts = mock(VerifyConstants.class);
        final Verificator verifyLinks = Mockito.spy(new Verificator(dao, verifyConsts));

        final List<Product> links = ImmutableList.of(
                createUmrsLink(true, 2042229422, dateTime));
        final List<Long> linkIds = links.stream().map(Product::getProductId).collect(Collectors.toList());

        final List<Pair<ProductUmrs, VerifyProblem>> pairs = verifyLinks.verify(links);
    }

我想检查一次方法ProductVerifyLink.verification并使用对我来说必要的参数。如何使用MockitoJUnit做到这一点?

整个问题是此类(ProductVerifyLink)的对象是在内部创建的,而在我外部则无法影响它。

1 个答案:

答案 0 :(得分:0)

您无法使用Mockito验证私有方法,因此可以使用PowerMock

但是我建议您测试公共方法的返回值,因此也要测试包括私有方法在内的整个流程。