JUnit Easymock Unexpected Method Call

I am trying to set up a test in JUnit w / EasyMock and I am having a small problem that I cannot wrap my head with. I was hoping someone here would help.

Here is a simplified version of the method I'm trying to test:

public void myMethod() { //(...) Obj myObj = this.service.getObj(param); if (myObj.getExtId() != null) { OtherObj otherObj = new OtherObj(); otherObj.setId(myObj.getExtId()); this.dao.insert(otherObj); } //(...) } 

Ok, so with EasyMock I made fun of calling service.getObj(myObj) , and it works great.

My problem occurs when JUnit gets into the dao.insert(otherObj ) call. EasyMock drops *Unexpected Method Call* .

I would not mind mocking this dao in my test and use expectLastCall().once(); on it, but it assumes that I have a handle to "otherObj", which is passed as a parameter during insertion ... Which, of course, I do not, because it is conditionally created in the context of the method being tested.

Has anyone had to deal with this and somehow solve it?

Thanks.

+6
methods junit easymock call
source share
4 answers

If you cannot get a reference to the object itself in your test code, you can use EasyMock.anyObject() as the expected argument for your insert method. As the name suggests, he will expect the method to be called using ... well, any object :)

This may be a little less stringent than matching the exact argument, but if you're happy with it, let it spin. Remember to include the cast in OtherObj when declaring the expected method call.

+9
source share

You can also use EasyMock.isA(OtherObj.class) to provide greater type safety.

+12
source share

The anyObject () connector works fine if you just want to go through this call, but if you really want to test the constructed object, then you thought it would be, you can use Capture. It would look like this:

 Capture<OtherObj> capturedOtherObj = new Capture<OtherObj>(); mockDao.insert(capture(capturedOtherObj)); replay(mockDao); objUnderTest.myMethod(); assertThat("captured what you expected", capturedOtherObj.getValue().getId(), equalTo(expectedId)); 

In addition, PowerMock has the ability to expect an object to be created, so you could explore this if you want.

+5
source share

Please also note that if you use EasyMock.createStrictMock(); , the order of the method calls is also important, and if you break this rule, it will cause an unexpected method call.

+1
source share

All Articles