简体   繁体   English

在实体框架中测试视图模型

[英]Testing a View model in Entity framework

I've generated a CRUD operation in entity frame work in MVC4. 我已经在MVC4的实体框架中生成了CRUD操作。 Now I'm testing that class. 现在,我正在测试该课程。 I am using the following code in controller for Details . 我在控制器中将以下代码用于Details

   public ActionResult Details(int id = 0)
    {
        Member member = db.Members.Find(id);
        if (member == null)
        {
            return HttpNotFound();
        }
        return View(member);
    }

And my test code, 还有我的测试代码

    [TestMethod]
    public void Details()
    {
        MemberController me = new MemberController();
        var mem = new Member();
        int id = 1;
        var result = (RedirectToRouteResult)me.Details(id);
         Assert.AreEqual("Index", result.RouteValues["action"]);
    }

While testing it shows, 测试表明,

Test Failed: Details 测试失败:详细信息

Message: Test method SampleTest.MemberTest.Details threw exception: 消息:测试方法SampleTest.MemberTest.Details抛出异常:

System.InvalidCastException: Unable to cast object of type 'System.web.Mvc.ViewResult' to >type 'System.Web.mvc.RedirectToRoutResult' System.InvalidCastException:无法将类型为“ System.web.Mvc.ViewResult”的对象转换为类型为“ System.Web.mvc.RedirectToRoutResult”的对象

Can anybody please help me to identify the problem? 有人可以帮我找出问题吗?

You return a ViewResult from the action, and try to case it to RedirectToRoutResult the test. 您从操作中返回一个ViewResult ,并尝试将其区RedirectToRoutResult测试的RedirectToRoutResult


That has nothing to do with the Entity Framework, but still, I usually avoid using EF objects as the model, for several reasons: 这与实体框架无关,但是出于以下几个原因,我通常仍避免使用EF对象作为模型:

  • Difficulty in decorating the classes with attributes (if you are using data annotation) 难以用属性修饰类(如果使用数据注释)
  • Serialization almost always fails: Member is an Employee who has a Manager who have a Department which has Room s... It never ends. 序列化几乎总是失败: Member是拥有ManagerEmployee ,而拥有ManagerDepartment却拥有Room
  • Easier to make security mistakes when MVC created and populated your entities after a POST. MVC在POST之后创建并填充您的实体时更容易犯安全错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM