Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EasyMock: supplying arguments you don't know at compile-time

Tags:

java

easymock

Using the latest version of EasyMock, I have a method that I need to stub out. The method takes an object parameter and returns void.

The stubbed method is being called by the method I'm testing. No surprises there. My difficulty is that the object that is supplied as an argument to the mocked method is being created by the method I'm testing.

I know I can get around this using createNiceMock() but is there a way to explicitly stub out this method?

Sample code:

public interface IMockMe { 
    void doSomething(InnerObj obj);
}

public class TestMe {
    IMockMe mockMe; 

    public void testThisMethod() {
        InnerObj obj = new InnerObj();
        mockMe.doSomething(obj);
    }
}

class Tester {
    @Test
    public void testThatDarnedMethod() {
        IMockMe mocked = EasyMock.create(IMockMe.class);

        mocked.doSomething( /* what goes here? */);
        EasyMock.expectLastCall();

        TestMe testMe = new TestMe(mocked);
        testMe.testThisMethod();

    }
}
like image 545
roufamatic Avatar asked Jan 27 '10 16:01

roufamatic


People also ask

Which among the following are benefits of using EasyMock?

Benefits of EasyMockNo Handwriting − No need to write mock objects on your own. Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime. Return value support − Supports return values. Exception support − Supports exceptions.

How does EasyMock capture work?

EasyMock has a feature called Capture which allows us to capture the arguments with which mocks are called, such that we can verify the argument values after having exercised the object being tested.

What does EasyMock expect do?

The expect() method tells EasyMock to simulate a method with certain arguments. The andReturn() method defines the return value of this method for the specified method parameters. The times() method defines how often the Mock object will be called.


1 Answers

Have a look at the "Flexible Expectations with Argument Matchers" section of the EasyMock documentation. Sample from the documentation:

String[] documents = new String[] { "Document 1", "Document 2" };
expect(mock.voteForRemovals(aryEq(documents))).andReturn(42);

The aryEq(documents) is a call which creates a matcher which will match any array with the right contents, rather than matching by identity.

In your case, you may want the anyObject() matcher.

like image 112
Jon Skeet Avatar answered Sep 18 '22 16:09

Jon Skeet