Skip to content

Instantly share code, notes, and snippets.

@gahrae
Last active August 4, 2018 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gahrae/526b02c909d584f100d22758c9054eed to your computer and use it in GitHub Desktop.
Save gahrae/526b02c909d584f100d22758c9054eed to your computer and use it in GitHub Desktop.
Demonstrate using EasyMock to mock a method argument modification.
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Assert;
import org.junit.Test;
/*
* Demonstrate using EasyMock to mock a method argument modification.
*/
// Dependency to mock...
class Service {
public boolean update(StringBuilder builder) {
// Challenge: Need to mock the mutation performed on the method argument.
builder.append("the change");
return true;
}
}
// Class under test...
class Example {
private Service service;
public void setService(Service service) {
this.service = service;
}
// Method under test
public String doSomething() {
// Uses a service to perform work but instead of just returning a result it modifies a method argument.
StringBuilder builder = new StringBuilder();
service.update(builder);
return builder.toString();
}
}
// JUnit verifying behavior of class 'Example'...
public class ExampleTest {
@Test
public void testChangeToMethodArgument() throws Exception {
final String expectedData = "the change";
Service service = EasyMock.createNiceMock(Service.class);
EasyMock.expect(service.update(EasyMock.anyObject(StringBuilder.class))).andAnswer(new IAnswer<Boolean>() {
public Boolean answer() throws Throwable {
// Retrieve the argument to to Service.update()
StringBuilder buffer = (StringBuilder) EasyMock.getCurrentArguments()[0];
// Mock change that would be applied by the method
buffer.append(expectedData);
return true;
}
});
EasyMock.replay(service);
Example example = new Example();
example.setService(service);
Assert.assertEquals(expectedData, example.doSomething());
}
}
@Thangaprabhu
Copy link

Work Like Charm... Nice Example

@utkgup24
Copy link

utkgup24 commented Aug 4, 2018

great example...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment