简体   繁体   中英

Testing a View model in Entity framework

I've generated a CRUD operation in entity frame work in MVC4. Now I'm testing that class. I am using the following code in controller for 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:

System.InvalidCastException: Unable to cast object of type 'System.web.Mvc.ViewResult' to >type '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.


That has nothing to do with the Entity Framework, but still, I usually avoid using EF objects as the model, for several reasons:

  • 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.
  • Easier to make security mistakes when MVC created and populated your entities after a POST.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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