Mockit 到 Mockito:使用 Mockito 进行枚举常量方法实现计数

问题描述 投票:0回答:1
public void testActionsThatNeedVerifyingPermissionsBeforeExecution()
    {
        IntegerWrapper value = new IntegerWrapper(0);
        new MockUp<HyperlinkActionType>()
        {
            @SuppressWarnings("ParameterHidesMemberVariable")
            @Mock
            void performActionIfApplicable(String entityId)
            {
                value.increment();
            }
        };

        //noinspection ConstantConditions
        Arrays.stream(HyperlinkActionType.values()).forEach(action -> action.invokeRequest(null));

        Assert.assertEquals("Except SAVE all other actions need to pass through 'performActionIfApplicable'"
                ,1,value.getWrappedObject().intValue());
    }

枚举代码

public enum HyperlinkActionType
{
    EDIT("Edit") {
        @Override public void invokeRequest(String entityId)
        {
            performActionIfApplicable(
                    entityId);
        }

    }

////////////

    DONOTHING("Donothing") {
        @Override public void invokeRequest(String entityId)
        {
            
        }
    }
    public void invokeRequest(String entityId)
    {
    }

    void performActionIfApplicable(String entityId) 
        {
                  ...

        }

}

此测试在 Enum.values 上运行 invokeRequest 方法,并期望 PerformActionIfApplicable 的计数为 1 我正在研究java17,我们正在迁移到jmockit到mockito。

我期望在两个枚举常量(enum.values)上调用invokeRequest时得到计数1,因为编辑只能通过invokeRequest执行ActionIfApplicable

解决方案: 监视每个枚举值

junit mockito java-17 jmockit
1个回答
0
投票

监视每个枚举值并使用 doAnswer 来增加 a 值

    @Test
    public void testActionsThatNeedVerifyingPermissionsBeforeExecution()
    {

        int actionsThatNeedVerificationBeforeExecution = 0;
        for (HyperlinkActionType hyperlinkActionType : HyperlinkActionType.values()) {
            actionsThatNeedVerificationBeforeExecution += testEachActionTypeForVerification(hyperlinkActionType);
        }
        Assert.assertEquals("Except DONOTHING all other actions need to pass through 'performActionIfApplicable'"
                , 1, actionsThatNeedVerificationBeforeExecution);
    }

    private int testEachActionTypeForVerification(HyperlinkActionType edit)
    {
        HyperlinkActionType spyiedAction = Mockito.spy(edit);
        IntegerWrapper willVerify = new IntegerWrapper(0);

        Mockito.doAnswer((i) -> {
                    willVerify.increment(); // This will only increment if performActionIfAvailable is called
                    return null;
                })
                .when(spyiedAction)
                .performActionIfApplicable(Mockito.isNull());

        spyiedAction.invokeRequest(null);
        return willVerify.getWrappedObject().intValue(); //it will return 1 if performACtionIfApplicable is called othewise ZERO
    }
© www.soinside.com 2019 - 2024. All rights reserved.