本文介绍了单元测试嘲弄问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我试图测试的方法但是它失败了Employee.CurrentEmployee.IsManager这是一个从嵌套类中获取的布尔值,它依赖于会话,因此当我为此运行单元测试时它会失败,因为它有当我运行单元测试时没有创建会话所以我尝试模拟对象



below is the method i tried to test but it fails for Employee.CurrentEmployee.IsManager this is a boolean value being fetched from a nested class which is dependent on the session so when i run unit test for this it fails cause there is no session created while i am running unit test so i tried mocking the object

public ActionResult IndexCompleted(PlanModel model)
        {
            int PlanID = model.Plan.PlanID;
            ViewBag.Title = "Plan Number: " + PlanID;
            //Only managers can access the plans (the bride now works at the chapel)
            if ((PlanID == 387484 || PlanID == 765675 || PlanID == 872095 || PlanID == 900535) && !Employee.CurrentEmployee.IsManager)
            {
                return Content("Unauthorized");
            }
            return View(model);
        }





我的尝试:



i我正在尝试创建一个模拟对象,但却因为我没有界面而创建它



What I have tried:

i am trying to create a mock object butfailing to create it cause i don't have a interface

[Test]
        public void FetchingPlanModelObjectIfYouAreManagerElseUnauthorized()
        {
            PlanController planController = new PlanController();
            PlanModel planmodel = new PlanModel()
            {
                Plan = new LittleChapel.Plan()
                {
                    PlanID = 387484
                }
            };
            Mock<iemployee> objMock = new Mock<iemployee>();
            objMock.Setup(x => Employee.CurrentEmployee.IsManager).Returns(true);
            //objMock.SetupProperty(x => x.IsManager,true);
            //objMock.Setup(x=>x.IsManager).Returns(true);
            var plan = planController.IndexCompleted(planmodel) as ViewResult;
            Assert.AreEqual(planmodel, plan.ViewData.Model);
        }

推荐答案

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;
   }
 }
}


这篇关于单元测试嘲弄问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:55