开发者

Getting exception from EasyMock's "nice mock" with a debugger attached

开发者 https://www.devze.com 2023-03-09 01:35 出处:网络
(Disclaimer - EasyMock newb) According to the documentation (and this post), if I wanted to use EasyMock to generate stub objects, I should use EasyMock.createNiceMock(). A "nice mock" is ac

(Disclaimer - EasyMock newb)

According to the documentation (and this post), if I wanted to use EasyMock to generate stub objects, I should use EasyMock.createNiceMock(). A "nice mock" is actually a stub - i.e an object that doesn't participate in validation, just returns values.

However, the following snippet fails for me with an IllegalStateException("missing behavior definition for the preceding method"), on the second foo.translate() line.

Foo foo = EasyMock.createNiceMock(Foo.class);
EasyMock.replay(foo); // added this line
foo.translate("a", "b");
foo.translate("a", "b"); // only the second calls throws an exception

Can anyone explain this, or rather tell me how to use EasyMock to create stubs with zero verbosity (o(number_of_exercised_mock_metho开发者_JS百科ds)).

Edit - I've noticed that I'm getting these errors almost always when a debugger is attached, but never when it isn't attached. Any idea how that may be related?


Complementing on Jeff's answer.

From EasyMock's method createNiceMock javadoc:

Creates a mock object that implements the given interface, order checking is disabled by default, and the mock object will return 0, null or false for unexpected invocations.

A mock object created by this method don't need any configuration (expected invocations). You just have to create it and "replay it". Example:

ComplicatedObject stub = EasyMock.createNiceMock();
replay(stub);

Any method call is allowed on the created stub (it won't throw an Exception), and they will always return the default value (0, null or false). If you set up an specific invocation expectation, then you'll have to configure it's return value or you'll get an error (that's your case).

If you want to restrict which methods can be executed (making the test fail if an unexpected method is called), them I'm afraid you'll have to create a regular mock, set up every invocation expectation and a return value for each of those.


If your translate method returns a value, you need to setup an expectation for it.

expect(foo.translate("a","b")).andStubReturn(retVal);


You need to call EasyMock.replay(foo). Before you do that your mock object is in a "record state". From EasyMock documentation:

In the record state (before calling replay), the Mock Object does not behave like a Mock Object, but it records method calls. After calling replay, it behaves like a Mock Object, checking whether the expected method calls are really done.

If you with to create a stub object just call createNiceMock followed by replay:

Foo foo = EasyMock.createNiceMock(Foo.class);
EasyMock.replay(foo);
foo.translate("a", "b");
foo.translate("a", "b");
0

精彩评论

暂无评论...
验证码 换一张
取 消