1

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?

geronimo
  • 839
  • 1
  • 9
  • 19
  • Maybe your example is too simple to understand the actual problem here, but why do you not have a handle on the `getName` method? Do you really not know how many times it can be called in this context? Is it really going to be more than just once? – mystarrocks Feb 13 '15 at 17:20
  • My example is indeed simplified, and of course I can count how many times that method is called. Point is: I do not want the unit test to depend on adding/changing or even enabling/disabling logging output. More general: I want to exclude some methods from the "strict" order. – geronimo Feb 18 '15 at 19:20

1 Answers1

1

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.

Will
  • 390
  • 4
  • 13
  • 1
    Thanks, I didn't know that `andStubReturn` method, this is exactly what I needed! I also found this post to explain the difference between that method and `andReturn`: http://stackoverflow.com/questions/3740376/easymock-andreturn-vs-andstubreturn – geronimo Dec 14 '15 at 08:55