什么重构会使这个方法可测试

时间:2011-07-04 11:22:35

标签: c#-4.0

所以我有

 /// <summary>
        ///We cannot sell to someone who's address postcode is Channel Islands = GY 
        /// or Isle of Man = IM.
        /// So there are three possibilities... an unclear channel islands I.D. needs a pop up, an error or invalid country needs a pop up and a good match can display policyholder
        ///
        /// </summary>
        public void ValidateAddressCanPurchaseInsurance(PolicyHolder p)
        {
            if (p == null) {DisplayErrorPopup(@"Could not check address for this person - Dang!"); return;}

            var countryResult = IdentifyUnavailableAddresses(p);

            if (countryResult == UnavailableAddressMatch.UnmatchedChannelIslands) {DisplayErrorPopup("Couldn't determine whether this Channel Islands resident is Jersey or Guernsey based... fix postcode and retry application"); return;}
            if (countryResult == UnavailableAddressMatch.Guernsey || countryResult == UnavailableAddressMatch.IsleOfMan) { DisplayErrorPopup(countryResult); return;}
            if (countryResult == UnavailableAddressMatch.None) { DisplayPolicyHolder(p); return; }
            DisplayErrorPopup(String.Format("Something very odd has gone on while trying to validate the address of this person! {0}",p.MembershipNumber));
        }

我无法真正测试...我显然可以测试IdentifyUnavailableAddresses()但是我想将一组policyHolders传递给此方法并看到它的行为符合我的预期。

显示错误弹出窗口将采用UnavailableAddressMatch枚举并适当格式化弹出消息或将字符串放入弹出窗口中

此方法位于确定Windows窗体行为的类中......

2 个答案:

答案 0 :(得分:2)

我同意Sjoerd的观点,即DisplayErrorPopUp不属于本课程。但我会更进一步说,对DisplayErrorPopUp的呼吁也不属于此。我会说这个方法应该抛出一个异常,调用者应该捕获并显示一条错误消息,具体取决于异常。您可能希望在不同视图中处理不同的异常。

编辑:哦,你测试的是该方法正在抛出正确的异常。您不必关心DisplayErrorPopup,因为在视图测试中测试了如何处理不同的异常。

答案 1 :(得分:0)

ValidateAddressCanPurchaseInsurance是一种业务层方法。 DisplayErrorPopup是一个UI用户。他们不属于同一类。

DisplayErrorPopup放在另一个类中可以在单元测试中放置一个模拟对象,并检查是否调用了DisplayErrorPopup