开发者

How to stub a method in Mockito whose name is not known until runtime?

I'd like to test that every method with a known prefix in a specific class is called during a particular test.

I can't work out a way to use mockito to stub out a method or how to verify that method has been called when the method name is not known until runtime.

The code below shows how I can get the methods I'd like to stub:

Method[] methodArr = customValidation.getClass().getDeclaredMethods();
loop: for (Method method : methodArr) {
    if (method.getName().startsWith("validate")) {
        // then stub out this method and check whether it gets called
        // after we run some code
    }
}

The question is, 开发者_如何学Chow can I stub them without know the method names until runtime?

Has anyone done anything like this before or have a good idea of how it can be done?

Many Thanks


This does not appear to be possible as of now. There is an unresolved enhancement request


For anyone who's interested, the solution I used was to use regular mocking to stub my methods:

UserBeanValidation userBeanValidation = Mockito.mock(UserBeanValidation.class);
Mockito.when(userBeanValidation.validateUserId(Mockito.anyString())).thenReturn(validationError);

I verified they were called once and incremented a count whenever one of the stubbed methods was executed. This count could be compared with a count of methods with a specific prefix to ensure all expected methods were called:

int totalMethodCount= 0;
Method[] methodArr = customValidation.getClass().getDeclaredMethods();
loop: for (Method method : methodArr) {

    if (method.getName().startsWith("validate")) {
        totalMethodCount++;
    }
}

Assert.assertEquals(totalMethodCount, calledMethodCount);

This way I can be sure that all my methods are called... now to find out if they do what they're supposed to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜