java 测试没有使用 EasyMock 调用 void 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3710717/
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
Test that void method didn't get called with EasyMock
提问by nkr1pt
Is this possible?
I tried with EasyMock.expectLastCall().times(0);
but EasyMock complains that times must be >=1
这可能吗?我试过了,EasyMock.expectLastCall().times(0);
但 EasyMock 抱怨时间必须 >=1
采纳答案by nkr1pt
I managed to come up with a solution:
我设法想出了一个解决方案:
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
Assert.assertFail();
return null;
}
});
回答by Dawood ibn Kareem
You could use .andThrow(new AssertionFailedError()).anyTimes();
- this is the same exception that Assert.fail()
throws, but is less verbose than making an Answer
.
您可以使用.andThrow(new AssertionFailedError()).anyTimes();
- 这与Assert.fail()
引发的异常相同,但比创建Answer
.
回答by David Nguyen
with easymock 3.0, you need to add a .anyTimes() on the expectLastCall or the test will fail:
使用 easymock 3.0,您需要在 expectLastCall 上添加 .anyTimes() 否则测试将失败:
Expectation failure on verify: myMethod(): expected: 1, actual: 0`
based on nkr1pt example:
基于 nkr1pt 示例:
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
Assert.assertFail();
return null;
}
}).anyTimes();
回答by Vic
The fact that some method is not called is controlled by Mock
or StrictMock
. They will throw an exception, when that not recorded method is called. This problem occurs only when using NiceMock
s, where default values are returned when calling for not recorded methods.
某些方法未被调用的事实由Mock
或控制StrictMock
。当未记录的方法被调用时,它们将抛出异常。此问题仅在使用NiceMock
s时发生,其中调用未记录的方法时返回默认值。
So a solution can be not to use NiceMock
s.
因此,解决方案可以是不使用NiceMock
s。
回答by Christian Strempfer
Looks like a bug to me. The internal class Range
does not allow to set a maximum less than 1.
对我来说看起来像一个错误。内部类Range
不允许设置小于 1 的最大值。
Couldn't you mock that method, and just call Assert.fail()
?
你不能嘲笑那个方法,然后打电话Assert.fail()
吗?
回答by Henri Tremblay
If you expect your method not to be called then just don't record it. But I agree it won't work with a nice mock.
如果你希望你的方法不被调用,那么就不要记录它。但我同意它不适用于一个很好的模拟。