EasyMock:模拟新操作可能吗?
是否可以使用 EasyMock 执行类似的操作:
class ClassName{
void method(){
TypeToMock a = new TypeToMock();
}
}
并且我想模拟 TypeToMock
而不将其作为值传递给类 ClassName
。是否可以?如果是这样怎么办?
Is it possible to do something like that with EasyMock:
class ClassName{
void method(){
TypeToMock a = new TypeToMock();
}
}
and I want to mock TypeToMock
without passing it as a value to class ClassName
. Is it possible? If so how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,我认为这是不可能的。
如果你想模拟一个依赖项,那么你必须将该依赖项注入到被测试的类中,无论是通过构造函数、通过 setter 方法还是直接作为参数注入到你想要测试的方法中。
如果您的类使用 new 创建它并且只执行一次,那么您应该使用为您提供最佳范围匹配的方法来注入依赖项。
如果您的类多次使用 new 创建对象,那么您可以注入一个工厂来生成对象实例。然后你可以提供一个模拟工厂来生成模拟实例。
No I don't think this is possible.
If you want to mock out a dependency then you have to inject that dependency into the class under test, either through the constructor, through a setter method or directly into the method you want to test as an argument.
If your class is creating this using
new
and only doing it once then you should inject the dependency using the method that gives you best match of scope.If your class is creating an object using
new
several times, then you could inject a factory which produces the objects instances instead. then you can provide a mock factory which produces mock instances.