且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单元测试嘲弄问题

更新时间:2023-11-16 22:53:16

你的控制器代码中有一些神奇的数字。为什么不在一些额外的课程中交换它,从而得到一些你可以模拟的界面。

例如



you have some magic numbers there in your controller code. Why don't you swap this out in some extra class, thereby you get some interface you can mock against.
e.g.

void Main()
{
	var a = new PlanAuthorizationProvider();
	var result = a.IsAuthorized(true, 387484);
	//result.Dump();   // this is for linqpad 
}

public interface IPlanAuthorizationProvider
{
  bool IsAuthorized(bool isManager, int planId);
}

public class PlanAuthorizationProvider : IPlanAuthorizationProvider
{
  public bool IsAuthorized (bool isManager, int planId)
  {
   // this goes in your app.config
   //  < appSettings >
   //    < add key = "managerOnlyPlanIds" value = "387484,765675,872095,900535" />
   //  </ appSettings >
   //string managerOnlyPlantIds = ConfigurationManager.AppSettings["managerOnlyPlanIds"];
   string managerOnlyPlanIds = "387484,765675,872095,900535";
   var listOfManagerOnlyPlanIds = 
          managerOnlyPlanIds.Split(',').Select(int.Parse).ToList();
   if (listOfManagerOnlyPlanIds .Contains(planId))
   {
     return isManager;
   }
   else
   {
     return true;
   }
 }	 
}