问题
Do all the methods that are not mocked on a mocked class work work as normal?
E.G.
Given the object
public class Shape {
public void createShape(...){
....
}
public void removeShape(...){
....
}
...
}
if this was mocked out like
shape = createMock(Shape.class, new Method[]{Shape.class.getMethod("removeShape", new Class[]{...})});
would all the other methods like createShape()
work or do you have to mock out all methods you want to use?
回答1:
In short, yes.
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.
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();
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.
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.
Hope that Helps
来源:https://stackoverflow.com/questions/19385924/easymock-partially-mocked-class