开发者

calling an Asp.net MVC 3 action method that updates a database in a unit testing method

Coders, I am in process of writing test cases for Asp.net MVC 3 project and I need call an action method that insert data into a database using Entity Framework. Here is the code for the action method:

//
    // POST: /School/Create

    [HttpPost]
    public ActionResult Create(School school)
    {
        if (ModelState.IsValid)
        {
            db.Schools.Add(school);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

        return View(school);
    }

And here is the code for my test method:

 [TestMethod]
    public void CreateNewSchool()
    {
        var schoolController = new SchoolController();
        var viewResult = schoolController.Index();

        //creating a school object
        School school = new School();
        school.Name = "OOO";

        //passing the school object to the action method
        schoolController.Create(school);

        //making sure that the model is not null
        Assert.IsNotNull(viewResult.Model);
    }

Notice, however, that I don’t check if the data were actually inserted in the database. I just check that the model of the view is not null. I do manually check the database using SQL server management studio.

The problem is though that when I call the action method in the test method to create/insert a record in the database nothing happened to the database. However, if I run the application and brows to the create page and try to create a new recorded then the record will be added to the database. So it appears to me that insertion to database happens only if I run the application and actually brows to the create page and hit the create button, but I cannot programmatically call the action method in the test method to insert a new record in the database. I have also debugged the test case and it did hit the db.SaveChanges(); line in the action method, but no changes were reflected in the databa开发者_StackOverflow社区se.

So, can someone explain to me why I am not able to insert a record by calling the action method in my test method?

Thanks in advance.


I would look into how your db context is getting instantiated. In many cases, it is not desirable for unit tests to cause database round-trips, so people use strategies like mocking to prevent it. It might be something as simple as using a different connection string when you are running a unit test versus running it as an asp.net application.


Do you have any validation on the school class? I am guessing when you run it under the test environment that school is not valid and so ModelState.IsValid returns false and doesn't save.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜