为什么我验证静态方法20次都没有失败?

Why I can verify static method for 20 times and it doesn't fail?

这是我的测试代码:

public void testApplyListWhenAddTheSameIDThenReturnDuplicateEntityException(){
    MyEntity entityRCM = createMyEntity(AGE_ID, WEIGHT_ID, 0L);
    entityModel.addEntity(entityRCM);
    MyEntity entityOPC = createMyEntity(DIFF_AGE_ID, WEIGHT_ID, 0L);
    EntityCreate create = new EntityCreate(entityOPC);
    List<EntityChange> changeList = new ArrayList<EntityChange>();
    changeList.add(create);
    try {
        entityModel.apply(changeList);
        fail();
    }catch(DuplicateEntityException e) {
        PowerMockito.verifyStatic(times(20));
        LogManager.error(Mockito.<Logger>anyObject(),Mockito.anyString(),Mockito.<DuplicateEntityException>anyObject());
    }
}

问题在这里:

PowerMockito.verifyStatic(times(20));
LogManager.error(Mockito.<Logger>anyObject(),Mockito.anyString(),Mockito.<DuplicateEntityException>anyObject());

我想验证classLogManager中的一个静态方法error,但是这个方法怎么验证二十次都不失败

在评论中解决:

Did you add @PrepareForTest and mockStatic? If not, then you may have set up your matchers and static call but PowerMock never sees the actual call to mock before your test completes.

对于上下文,PowerMock 通过拦截 classloader 并加载调用 PowerMock 提供的 replacement class 来模拟静态 classes实现而不是原件。除非您添加正确的准备,否则 PowerMock 不会替换 class,因此它不会计算静态方法调用或识别要验证的方法,并且测试将在验证调用实际发生之前完成。