@Test public void shouldAddNewEmployee() {
mockEmployeeDAO.insert(employee);
replay(mockEmployeeDAO);
employeeBO.addNewEmployee(employee);
verify(mockEmployeeDAO);
}
@Test public void shouldUpdateEmployee() {
mockEmployeeDAO.update(employee);
replay(mockEmployeeDAO);
employeeBO.updateEmployee(employee);
verify(mockEmployeeDAO);
}
测试方法shouldAddNewEmployee用于验证测试对象(employeeBO )和Mock(mockEmployeeDAO )之间交互是否正确。它期望employeeBO调用mockEmployeeDAO中的insert方法,并将接收到的Employee实例传递给该方法。shouldAddNewEmployee方法虽然简单,但其中含有一些没有实际目的的代码,这为我们的测试带来了混乱:
重复调用replay,通知EasyMock所有期望的工作已完成。 重复调用verify,通知EasyMock所有期望的工作已验证完成。Mock的使用常常遵循下面的模式:
建立Mock和期望 执行要测试的代码 验证执行结果是否符合期望这种模式会在测试代码中引入重复,这在测试方法shouldAddNewEmployee()和shouldUpdateEmployee()中很明显。使用 EasyMockTemplate 可以减少代码混乱和重复:
/**
* Understands a template for usage of EasyMock mocks.
* @author Alex Ruiz
*/
public abstract class EasyMockTemplate {
/** Mock objects managed by this template */
private final List<Object> mocks = new ArrayList<Object>();
/**
* Constructor.
* @param mocks the mock objects this template will manage.
* @throws IllegalArgumentException if the list of mock objects is null or empty.
* @throws IllegalArgumentException if the list of mock objects contains a null value.
*/
public EasyMockTemplate(Object... mocks) {
if (mocks == null) throw new IllegalArgumentException("The list of mock objects should not be null");
if (mocks.length == 0) throw new IllegalArgumentException("The list of mock objects should not be empty");
for (Object mock : mocks) {
if (mock == null) throw new IllegalArgumentException("The list of mocks should not include null values");
this.mocks.add(mock);
}
}
/**
* Encapsulates the common pattern followed when using EasyMock.
* <ol>
* <li>Set up expectations on the mock objects</li>
* <li>Set the state of the mock controls to "replay"</li>
* <li>Execute the code to test</li>
* <li>Verify that the expectations were met</li>
* </ol>
* Steps 2 and 4 are considered invariant behavior while steps 1 and 3 should be implemented by subclasses of this template.
*/
public final void run() {
setUp();
expectations();
for (Object mock : mocks) replay(mock);
codeToTest();
for (Object mock : mocks) verify(mock);
}
/** Sets the expectations on the mock objects. */
protected abstract void expectations();
/** Executes the code that is under test. */
protected abstract void codeToTest();
/** Sets up the test fixture if necessary. */
protected void setUp() {}
}
文章来源于领测软件测试网 https://www.ltesting.net/