Mock为测试代码带来混乱和重复
下面的代码使用 EasyMock 测试:EmployeeBO用EmployeeDAO存储新员工信息和更新当前员工信息。
@Before public void setUp() { mockEmployeeDAO = createMock(EmployeeDAO.class); employeeBO = new EmployeeBO(mockEmployeeDAO); employee = new Employee("Alex", "CA", "US"); } @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); } }
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/