如何在 Mockito 中存根一个直到运行时才知道名称的方法?
我想测试在特定测试期间是否调用特定类中具有已知前缀的每个方法。
我无法找到一种方法来使用mockito 来存根一个方法,或者当方法名称直到运行时才知道时如何验证该方法已被调用。
下面的代码显示了如何获取我想要存根的方法:
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
}
}
问题是,如何在运行时之前不知道方法名称的情况下对它们进行存根?
有没有人以前做过类似的事情或者知道如何做到这一点?
非常感谢
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, how 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于任何感兴趣的人,我使用的解决方案是使用常规模拟来存根我的方法:
我验证了它们被调用一次,并在执行其中一个存根方法时增加计数。可以将此计数与具有特定前缀的方法计数进行比较,以确保调用所有预期的方法:
这样我可以确保调用了我的所有方法...现在找出它们是否执行了它们应该执行的操作。
For anyone who's interested, the solution I used was to use regular mocking to stub my methods:
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:
This way I can be sure that all my methods are called... now to find out if they do what they're supposed to.
目前看来这还不可能。有一个未解决的增强请求
This does not appear to be possible as of now. There is an unresolved enhancement request