EasyMock Capture Example
Thursday, September 2nd, 2010
Background
EasyMock version 2.4 introduced some new functionality – the ability to capture the arguments passed to mock objects. As ever a few lines of code speaks volumes.
Capture Example
Test Class
package foo.bar;
import static org.junit.Assert.assertEquals;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Before;
import org.junit.Test;
public class TestServiceImpl {
private Service service;
private Dao dao;
private IMocksControl controller;
private final String description = "description";
@Before
public void setUp() throws Exception {
controller = EasyMock.createStrictControl();
dao = controller.createMock(Dao.class);
service = new ServiceImpl();
service.setDao(dao);
}
@Test
public void testSave() {
Capture <DomainObject> capturedArgument = new Capture <DomainObject>();
dao.save(EasyMock.and(EasyMock.capture(capturedArgument), EasyMock.isA(DomainObject.class)));
controller.replay();
service.save(description);
controller.verify();
DomainObject record = capturedArgument.getValue();
assertEquals(description, record.getDescription());
assertEquals("getNextId", record.getId());
}
}
Source code for classes under test after the break…….
Service Interface
package foo.bar;
public interface Service {
void save(String description);
void setDao(Dao dao);
}
Service Implementation
package foo.bar;
public class ServiceImpl implements Service {
private Dao dao;
public void save(String description) {
DomainObject record = new DomainObject();
record.setDescription(description);
record.setId("getNextId");
dao.save(record);
}
public void setDao(Dao dao) {
this.dao = dao;
}
}
Dao Interface
package foo.bar;
public interface Dao {
public abstract void save(DomainObject record);
}
Dao Implementation
package foo.bar;
public class DaoImpl implements Dao {
public void save(DomainObject record) {
// do something
}
}
Domain Object (Bean)
package foo.bar;
public class DomainObject {
private String id;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
You can leave a response, or trackback from your own site.
Tags: easymock, java, testing
Posted in: Development, Examples
