java word 中的自动存根。 用什么?
我有一个巨大的课程,我需要为其构建存根。
给你看一下,它是 GWT 的 Messages 类。 通常,该类具有数十个返回 String 的方法。
使用 JMock,我可以进行存根操作,但我最终会允许每种方法......这不是我想看到的。
是否有东西可以自动为每个方法构建存根? 我需要这个方法来返回一些预定义的东西,比如空字符串,但我会很高兴收到任何建议。
I have huge class that I need to build stub for.
To give you picture it is Messages class of the GWT. Often this is class with dozens of methods that return String.
With JMock I can do stubbing, but I will end with allowing each method... This is not something that I would like to see.
Is there something that will automatically build the stubs for each method? I need this methods to return something predefined, like empty string, but I will be happy with any suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 JMock 中,您可以使用显式结果允许您关心的方法,然后使用不包含方法的允许语句允许消息对象的任何其他方法。 例如:
但是...
如果您只是存根一堆 getter 方法,那么模拟对象框架是错误的工具。 模拟对象用于测试被测对象是否向相邻对象发送正确的命令以影响其环境的变化。
如果接口只包含 getter,那么创建存根类通常会更容易。 或者您可以使用 Usurper 自动生成存根。
In JMock you can allow the methods you care about with explicit results and then allow any other method of the messages object with an allowing statement that does not include a method. E.g.:
But...
If you are just stubbing a bunch of getter methods, a mock object framework is the wrong tool to use. Mock objects are used for testing that the object under test sends the correct commands to neighbouring objects to effect change in its environment.
It's often easier to create a stub class if the interface that only contains getters. Or you can use Usurper to generate stubs automatically.
对于接口,您可以使用 java.lang.reflect.Proxy 的功能。 假设您想要对 MessageConstants 类的答案进行存根处理,代码将类似于:
并将导致
InvocableHandler 驱动存根处理,而其余部分只是管道处理。
For an interface you can use the functionality of java.lang.reflect.Proxy. Assuming that you want to stub answers for the MessageConstants class, the code will look similar to:
and will result in
The InvocationHandler drives the stubbing, while the rest is just plumbing.
很高兴看到你找到了答案。 欲了解更多信息,jMock 允许非常灵活地指定如何匹配方法,请参阅 http ://www.jmock.org/match-object-or-method.html。 例如,您可以执行此类操作:
匹配任何 getter。
S
Glad to see you found an answer. Just for further info, jMock allows quite flexible specifications of how you match methods, see http://www.jmock.org/match-object-or-method.html. For example, you can do this sort of thing:
to match any getter.
S
如果你使用EasyMock,你只需要为你实际期望被调用的方法指定behavior/expectations/stubs用过的。
在使用 JMock 和 EasyMock 后,我不得不说 EasyMock 的 API 易用性提高了大约 10 倍,而且由于接口主要是静态类型的,因此它的重构也很安全(您使用字符串作为方法名称等)。
If you use EasyMock, you only need to specify behavior/expectations/stubs for the methods you actually expect to be called and used.
After using both JMock and EasyMock, I have to say that EasyMock's API is about 10x easier to use, and since the interface is mostly statically-typed, it's refactoring safe as well (you are using Strings for method names, etc.).