Skip to content

Instantly share code, notes, and snippets.

@gahrae

gahrae/Example.java

Last active Aug 4, 2018
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Thangaprabhu Thangaprabhu commented Oct 24, 2017

Work Like Charm... Nice Example

@utkgup24

This comment has been minimized.

Copy link

@utkgup24 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