java Easymock:匹配器调用的使用超出预期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30780323/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:39:04  来源:igfitidea点击:

Easymock: matcher calls were used outside expectations

javaunit-testingjuniteasymock

提问by Lonzak

I changed the return value of a method in my code from voidto and Object. Then two junit test failed stating that an expect(...).andReturn(...)was missing. After adding those one test is fixed and the other still throws an exception which seems a bit weird:

我将代码中方法的返回值从voidto 和更改为Object。然后两个junit测试失败,说明expect(...).andReturn(...)缺少一个。在添加了那些测试之后,另一个测试仍然会抛出一个看起来有点奇怪的异常:

java.lang.IllegalStateException: matcher calls were used outside expectations

java.lang.IllegalStateException:在预期之外使用了匹配器调用

The code which works for one but not the other is:

适用于一个但不适用于另一个的代码是:

expect(myMock.foo(1l,FooEnum.A)).andReturn(EasyMock.anyObject(String.class));

Any ideas?

有任何想法吗?

采纳答案by Lonzak

I changed to code to

我改为代码

expect(myMock.foo(1l,FooEnum.A)).andReturn(new Object());

and now it works. It's still strange why I get this error since I definitely return a new Object(and not nullor anything)

现在它起作用了。为什么我收到这个错误仍然很奇怪,因为我肯定返回了一个new Object(而不是null任何东西)

回答by Karrde

EasyMock.anyObject(String.class)is a matcher, it isn't a Stringand can't be used as a Stringexcept for matching - matching being something like the following:

EasyMock.anyObject(String.class)是匹配器,它不是 aString并且不能用作 aString除了匹配 - 匹配类似于以下内容:

when(foo.bar(EasyMock.anyObject(String.class))).thenReturn("foo-bar")

P.S. you should avoid using new String()whenever possible; it's always better to use ""instead.

PS你应该new String()尽可能避免使用; 使用它总是更好""

回答by Nick Predey

I was having this same problem with an AmazonSQSClientobject. I tried .andReturn(new Object()), but got an incompatible type error. To fix this, simply return a new object of the type the method expects:

我对一个AmazonSQSClient对象也有同样的问题。我试过了.andReturn(new Object()),但遇到了不兼容的类型错误。要解决此问题,只需返回该方法期望的类型的新对象:

expect(amazonSQSClient.getQueueAttributes(queueUrl, attributeNames)).andReturn(new GetQueueAttributesResult());

expect(amazonSQSClient.getQueueAttributes(queueUrl, attributeNames)).andReturn(new GetQueueAttributesResult());