EasyMock:部分模拟的类 [英] EasyMock: Partially mocked class

查看:103
本文介绍了EasyMock:部分模拟的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是在模拟类上模拟的所有方法都能正常工作吗?

Do all the methods that are not mocked on a mocked class work work as normal?

EG

给出对象

public class Shape {
    public void createShape(...){
        ....
    }

    public void removeShape(...){
        ....
    }

    ...
}

如果这像

shape = createMock(Shape.class, new Method[]{Shape.class.getMethod("removeShape", new Class[]{...})});

是否可以使用所有其他方法,例如 createShape()工作还是您必须模拟出要使用的所有方法?

would all the other methods like createShape() work or do you have to mock out all methods you want to use?

推荐答案

总之,是的。

部分模拟的工作方式与模拟类的实例完全相同,但是它们能够为您设置为模拟的方法增加期望。
当您有一个重写方法也依赖于该方法的超类实现时,这通常会很有用。

Partial Mocks work exactly like an instance of the mocked class, but they have the ability to add expectations for the method you have set as mocked. This is usually helpful when you've got an overriding method that also relies on the super class implementation of that method.

看起来您的示例正在使用不推荐使用的createMock(Class,Method ...)方法,因此,我将提供一个示例,说明如何为Shape类创建部分模拟。

It looks like your example is using the deprecated createMock(Class, Method...) method, so I'll provide an example of how you should create a partial mock for your Shape class.

final IMockBuilder<Shape> mockBuilder = EasyMock.createMockBuilder(Shape.class);
mockBuilder.addMockedMethod(Shape.class.getMethod("removeShape", new Class[]{...}));
final Shape mockShape = mockBuilder.createMock();

这将提供一个Shape对象,该对象的行为正常,直到尝试使用removeShape方法为止,其中

This will provide a Shape object that behaves perfectly normally, until it tries to use the removeShape method, where it will require some expectations for the behaviour.

就我个人而言,我很少使用带有Method参数的addMockedMethod版本。通常,我要嘲笑的方法足以使用addMockedMethod(String)版本。因此,我最有可能使用以下代码:

Personally, I very rarely use the addMockedMethod version that takes a Method parameter. Usually, the method I'm mocking is distinct enough to use the addMockedMethod(String) version. So I would most likely use the following:

final IMockBuilder<Shape> mockBuilder = EasyMock.createMockBuilder(Shape.class);
mockBuilder.addMockedMethod("removeShape");
final Shape mockShape = mockBuilder.createMock();

这对我来说更干净一点,并且达到相同的效果。

This is a little cleaner to my eyes and achieves the same results.

请记住,这些部分模拟与完全模拟一样遵循相同的规律。
因此,您无法模拟这样的最终方法。

Keep in mind though, these partial mocks live by the same laws as full mocks do. So you can't mock out final methods like this.

希望有帮助

这篇关于EasyMock:部分模拟的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆