编程总结

1、每个方法中都要非常注意异常出现的情况。如:

private HashMap<QName, URI> getOperationsFromDescription(Description desc, QName serviceName) {
  HashMap<QName, URI> operations = new HashMap<QName, URI>();
  Interface interf = desc.getService(serviceName).getInterface();
  InterfaceOperation interfaceOpers[] = interf.getAllInterfaceOperations();
  
  //将interface中所有的operation都加入列表
  for (InterfaceOperation operation : interfaceOpers)
   operations.put(operation.getName(), operation.getMessageExchangePattern());
  return operations;
 }

    若desc.getService(serviceName)返回为null,则desc.getService(serviceName).getInterface();
将抛出异常。同样,若interf  为null, interf.getAllInterfaceOperations();也将抛出异常。

    所以,在方法中的每一步都应考虑异常的发生。

2、某些冗长的代码可简化,如:

if(file.exists())
   retrun tue;
//可直接改写为
return file.exists();

 3、单元测试应尽量保证每一测试方法只测某一方法的功能,若要被测方法的执行必须要先执行其它方法以准备数据,那么这种情况下,就可以为被测函数准备些mock数据。如要测以下方法:

/**
	 * 卸载组件的InstallerMBean
	 * @return 卸载成功返回true
	 * @param componentName
	 *            用以鉴别组件installer的组件名 不可为空字符串,不可为null。
	 * @param isToBeDeleted
	 *            <code>true</code> 如果值为true则将与InstallerMBean相对应的组件也卸载掉。
	 */
	public boolean unloadInstaller(String componentName,boolean isToBeDeleted) {
		//TODO:完成组件installerMBean的注销
		try {
			//如果值为true,则卸载相应的组件
			if (isToBeDeleted){
				ObjectName objectName=loadInstaller(componentName);
				if (objectName!=null) {
					EnvironmentAccess.getEnvironmentContext().getMBeanServer().invoke(objectName, "uninstall", null, null);
				}
			}
			getInstallManager().removeInstaller(componentName);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

     要测此方法,就要先安装一个组件,是RuntimeComponent在组件框架中存在,这样loadInstaller(componentName);语句才能返回要卸载组件的ObjectName 。为测此方法,要首先执行其它方法准备数据,这违背了单元测试的原则。

     正确的做法是InstallManager类做一个接口(可以将接口命名为InstallManager,将类InstallManager改名为InstallManagerImpl),然后再做一个Mock类:Class MockInstallationManager()implements InstallManager。测试方法里就可以通过MockInstallationManager.loadNewInstaller()为unloadInstaller()方法准备一个假的ObjectName;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值