java 在非常简单的示例中使用 EasyMock.expect() 时编译错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7204829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compile error while using EasyMock.expect() in very simple example?
提问by Bjarke Freund-Hansen
I am trying a very simple example using EasyMock, however I simply cannot make it build. I have the following test case:
我正在尝试使用EasyMock 的一个非常简单的示例,但是我根本无法构建它。我有以下测试用例:
@Test
public void testSomething()
{
SomeInterface mock = EasyMock.createMock(SomeInterface.class);
SomeBase expected = new DerivesFromSomeBase();
EasyMock.expect(mock.send(expected));
}
However I get the following error in the EasyMock.expect(...
line:
但是,我EasyMock.expect(...
在行中收到以下错误:
The method expect(T) in the type EasyMock is not applicable for the arguments (void)
Can somebody point me in the correct direction? I am completely lost.
有人可以指出我正确的方向吗?我完全迷失了。
回答by Jasper
If you want to test void
methods, call the method you want to test on your mock. Then call the expectLastCall()
method.
如果要测试void
方法,请在模拟上调用要测试的方法。然后调用expectLastCall()
方法。
Here's an example:
下面是一个例子:
@Test
public void testSomething()
{
SomeInterface mock = EasyMock.createMock(SomeInterface.class);
SomeBase expected = new DerivesFromSomeBase();
mock.send(expected);
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
public Object answer() {
// do additional assertions here
SomeBase arg1 = (SomeBase) EasyMock.getCurrentArguments()[0];
// return null because of void
return null;
}
});
}
回答by Biju Kunjummen
Since your send() method returns void, just call the mock method with expected values and replay:
由于您的 send() 方法返回 void,只需使用预期值调用模拟方法并重播:
SomeInterface mock = EasyMock.createMock(SomeInterface.class);
SomeBase expected = new DerivesFromSomeBase();
mock.send(expected);
replay(mock);
回答by Joshua Marble
Since you are mocking an interface, the only purpose in mocking a method would be to return a result from that method. In this case, it appears your 'send' method's return type is void. The 'EasyMock.expect' method is generic and expects a return type, which is causing the compiler to tell you that you can't use a void method because it doesn't have a return type.
由于您正在模拟接口,因此模拟方法的唯一目的是从该方法返回结果。在这种情况下,您的“发送”方法的返回类型似乎是无效的。'EasyMock.expect' 方法是通用的并且需要返回类型,这导致编译器告诉您不能使用 void 方法,因为它没有返回类型。
For more information, see the EasyMock API documentation at http://easymock.org/api/easymock/3.0/index.html.
有关更多信息,请参阅位于http://easymock.org/api/easymock/3.0/index.html的 EasyMock API 文档。
回答by Mike Partridge
You can't script methods with a void return in that way; check out this questionfor a good answer on how you can mock the behavior of your send
method on your expected
object.
您不能以这种方式编写带有 void 返回值的方法;查看这个问题以获得关于如何send
在expected
对象上模拟方法行为的好答案。