使用IOC测试MVC Controller的问题

时间:2014-06-26 06:28:16

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我正在使用IOC Unity测试我的控制器代码。问题在于我将模型初始化为传递给控制器​​的构造函数。

这是我在测试项目中的代码

  [TestMethod]
        public void TestHomeControllerIndexMethod()
        {
            HomeController controller = new HomeController(new stubPeopleService());
            ViewResult result = controller.Index() as ViewResult;

            Assert.AreEqual(0, result);
        }

下面是我创建的stubPeopleService的代码,我将其传递给上面的控制器构造函数

  public class stubPeopleService : IPeople
        {

            public int Age
            {
                get;
                set;
            }

            public string BirthPlace
            {
                get;
                set;
            }

            public DateTime DateOfBirth
            {
                get;
                set;
            }

            public int GetAge(DateTime reference, DateTime birthday)
            {
                int age = reference.Year - birthday.Year;
                if (reference < birthday.AddYears(age)) age--;

                return age + 1;
            }

            public int Height
            {
                get;
                set;
            }

            public List<People> listPeople { get { return GetPeople(); } }

            public string Name
            {
                get;
                set;
            }

            public int Weight
            {
                get;
                set;
            }

            private List<People> GetPeople()
            {

                List<People> list = new List<People>();
                list.Add(new People
                {
                    Name = "Ranjit Menon",
                    DateOfBirth = DateTime.Today,
                    BirthPlace = "London",
                    Age = 25,
                    Height = 175,
                    Weight = 85
                });


                return list.OrderBy(x => x.Name).ToList();
            }

        }

当我调试我的测试时,我注意到所有属性都不包含任何值。包含值的唯一属性是listPeople属性。 listpeople属性确实初始化其他属性,但抛出一个对象无法创建错误。让我知道我是否正确地进行了测试。我需要用一些值来初始化模型。

我家控制器的代码

       private IPeople peopleService;

            public HomeController(IPeople people)
            {
                this.peopleService = people;
            }

 public ActionResult Index()
        {
            return View(peopleService);
        }

请找到下面的IPeople界面

public interface IPeople
    {
        int Age { get; set; }
        string BirthPlace { get; set; }
        DateTime DateOfBirth { get; set; }
        int GetAge(DateTime reference, DateTime birthday);
        int Height { get; set; }
        List<People> listPeople { get; }
        string Name { get; set; }
        int Weight { get; set; }
    }

0 个答案:

没有答案