Last active
August 4, 2018 07:20
-
-
Save gahrae/526b02c909d584f100d22758c9054eed to your computer and use it in GitHub Desktop.
Demonstrate using EasyMock to mock a method argument modification.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great example...