存根类 测试代码 java
为了证明这一点,我将重新编写上一个博客中的代码 (2)测试我的简单AddressService 。 情况相同, AddressService必须加载站点属性并确定是否返回地址:
public Address findAddress(int id) {
logger.info("In Address Service with id: " + id);
Address address = Address.INVALID_ADDRESS;
if (isAddressServiceEnabled()) {
address = addressDao.findAddress(id);
address = businessMethod(address);
}
logger.info("Leaving Address Service with id: " + id);
return address;
}
private boolean isAddressServiceEnabled() {
return new Boolean(propManager.findProperty("address.enabled"));
}
…除了,我要假装SitePropertiesManager被锁定在JAR文件中。
我之前提出的有关使遗留代码更具可测试性的所有观点仍然存在:您需要使用SpringFactoryBean实现进行依赖注入,并停止依赖静态工厂方法getInstance ()。 您还需要一种创建存根的方法,该存根允许您将代码与我们的流氓类愉快使用的数据库和文件系统隔离开 SitePropertiesManager 。 在这种情况下,由于该类被锁定在一个JAR文件中,因此您不能简单地提取一个接口,您必须更加狡猾并使用继承。 使用继承编写存根是很简单的,并且只需要几行代码,如下所示:
public class StubSitePropertiesUsingInheritance extends SitePropertiesManager {
private final Map<String, String> propMap = new HashMap<String, String>();
public void setProperty(String key, String value) {
propMap.put(key, value);
}
@Override
public String findProperty(String propertyName) {
return propMap.get(propertyName);
}
}
这里的主要思想是,现在我可以将存根实例多态注入到我的AddressService类中,而无需知道它已经被欺骗了。
public class LegacyAddressServiceUsingInheritanceTest {
private StubAddressDao addressDao;
private StubSitePropertiesUsingInheritance stubProperties;
private LegacyAddressService instance;
@Before
public void setUp() {
instance = new LegacyAddressService();
stubProperties = new StubSitePropertiesUsingInheritance();
instance.setPropertiesManager(stubProperties);
}
@Test
public void testAddressSiteProperties_AddressServiceDisabled() {
/* Set up the AddressDAO Stubb for this test */
Address address = new Address(1, "15 My Street", "My Town", "POSTCODE", "My Country");
addressDao = new StubAddressDao(address);
instance.setAddressDao(addressDao);
stubProperties.setProperty("address.enabled", "false");
Address expected = Address.INVALID_ADDRESS;
Address result = instance.findAddress(1);
assertEquals(expected, result);
}
@Test
public void testAddressSiteProperties_AddressServiceEnabled() {
/* Set up the AddressDAO Stubb for this test */
Address address = new Address(1, "15 My Street", "My Town", "POSTCODE", "My Country");
addressDao = new StubAddressDao(address);
instance.setAddressDao(addressDao);
stubProperties.setProperty("address.enabled", "true");
Address result = instance.findAddress(1);
assertEquals(address, result);
}
}
您可能会问:为什么不总是使用继承,答案是该技术的缺点是测试代码与野生的SitePropertiesManager类紧密耦合。 在这种情况下,这并不是什么大问题,作为一名务实的程序员,我想这并不重要,因为拥有整洁,经过测试和可靠的代码比拥有松散耦合的代码(但没有单元测试)要好。
(1)设计时未考虑单元测试。
(2)源代码可从GitHub获得:
git://github.com/roghughe/captaindebug.git
参考:来自Captain Debug's Blog的 JCG合作伙伴 Roger Hughes提供了有关为遗留代码创建存根的更多信息-测试技术7 。
相关文章 :
翻译自: https://www.javacodegeeks.com/2011/12/more-on-creating-stubs-for-legacy-code.html
存根类 测试代码 java