AspectJ 和模仿对象的测试灵活性:用“test-only”行为增强单元测试
2010-03-18 00:00:00 来源:WEB开发网我有意将这个单元写得简单一点,这样我们就可以将精力集中在测试上。 ClientBean 的接口与 CustomerManager 的接口只有一点点不同。与 ClientManager 不同, ClientBean 的 register() 方法将返回一个布尔值,而且在客户已经存在的时侯不会抛出异常。这些就是好的单元测试应该验证的功能。
清单 3 所示的代码将实现 ClientBean 的 JUnit 测试。其中有三个测试方法,一个是 getCustomers() 的,另外两个是 register() 的(其中一个是成功的,另一个是失败的)。测试假定 getCustomers() 将返回一个有 55 个条目的列表, register() 将为 EXISTING_CUSTOMER 返回 false ,为 NEW _CUSTOMER 返回 true 。
清单 3. ClientBean 的单元测试
//[...standard JUnit methods omitted...]
public static final String NEW_CUSTOMER = "Bob Smith";
public static final String EXISTING_CUSTOMER = "Philomela Deville";
public static final int MAGIC_AGE = 35;
public void testGetCustomers() throws Exception {
ClientBean client = new ClientBean();
String[] results = client.getCustomers(MAGIC_AGE);
assertEquals("Wrong number of client names returned.",
55, results.length);
}
public void testRegisterNewCustomer() throws Exception{
ClientBean client = new ClientBean();
//register a customer that does not already exist
boolean couldRegister = client.register(NEW_CUSTOMER);
assertTrue("Was not able to register " + NEW_CUSTOMER, couldRegister);
}
public void testRegisterExistingCustomer() throws Exception{
ClientBean client = new ClientBean();
//register a customer that DOES exist
boolean couldNotRegister = ! client.register(EXISTING_CUSTOMER);
String failureMessage = "Was able to register an existing customer ("
+ EXISTING_CUSTOMER + "). This should not be " +
"possible."
assertTrue(failureMessage, couldNotRegister);
}
更多精彩
赞助商链接