geronimo
geronimo

Reputation: 879

EasyMock: combine intermediate anyTimes with strict mock

I am wondering if it is possible to define behaviour in easyMock that permits "intermediate" method calls.

Suppose I want to verify the behaviour of the doSomething method in this class:

class MyObject {
    MyOtherObject inner; // init as constructor param...

    void doSomething() {
        inner.call1();
        inner.call2();
    }

    public String toString() {
        return "MyObject{" + inner.getName() + "}";
    }
}

I had this test code:

MyOtherObject mocked = EasyMock.createStrictMock(MyOtherObject.class);
MyObject obj = new MyObject(myOtherObject);

// methods need to be called in this order
EasyMock.expect(mocked.call1()).once();
EasyMock.expect(mocked.call2()).once();

obj.doSomething();

When I change the implementation of MyObject.doSomething() to add logging using the toString() method, my tests fail because I did not add an expectation for MyOtherObject.getName().

Since I need a strict mock (with method order checking), simply adding this will not work: EasyMock.expect(mocked.getName()).andReturn("blahblah").anyTimes().

Is there an elegant way to solve this? For now, I have added this "anyTimes()" statement before every "real" expectation, but it renders my test unreadable and hard to maintain.

Or should I switch to another test framework?

Upvotes: 1

Views: 689

Answers (1)

Will
Will

Reputation: 400

If you don't care about the method call, for example logging, you can exclude it from any verification using a stub. So:

EasyMock.expect(mocked.getName()).andStubReturn("blah");

This will prevent your test from breaking by returning a value, but will not factor in to any sort of mocking verification, including strict mock ordering.

Upvotes: 1

Related Questions