System.ArgumentNullException:值不能为null

时间:2012-10-09 03:21:01

标签: c# asp.net-mvc-3 unit-testing razor

我正在为我的CRUD创建一个单元测试并在我的删除测试方法中收到这种错误:

System.ArgumentNullException: Value cannot be null.

我检查并发现每当我运行测试时,我的userID下的内容已被删除,但在我的测试结果栏中收到“失败”状态。任何人都可以帮我解决我的问题吗?

Error Message: Test method TestProject1.UserTest.Delete threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: entity

这是我的代码:

[TestMethod]
public void Delete()
{
taskModelContainer db = new taskModelContainer();

int userID = 7;

TaskMgr.Models.User UserEntity = new TaskMgr.Models.User();

UserEntity.userID = userID;

UserController User = new UserController();

ActionResult result = User.DeleteConfirmed(UserEntity.userID);
int id = Convert.ToInt32(User.ViewBag.id);
User Users = db.Users.Single(e => e.userID == id);


Assert.IsNull(Users.userID);

}

控制器:

[HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        User user = db.Users.Find(id);
        db.Users.Remove(user);
        db.SaveChanges();
        var qry = from e in db.Users orderby e.userID descending select e.userID;
        int eID = qry.First();
        ViewBag.id = user.userID;
        return RedirectToAction("Index");
    }

它在控制器的这一行停止:db.Users.Remove(user);

1 个答案:

答案 0 :(得分:0)

我通过这样做解决了我的问题:

[TestMethod]
    public void Delete()
    {
        taskModelContainer db = new taskModelContainer();

        int userID = 41;

        TaskMgr.Models.User UserEntity = new TaskMgr.Models.User();

        UserEntity.userID = userID;

        UserController User = new UserController();

        ActionResult result = User.DeleteConfirmed(UserEntity.userID);

        var del = from e in db.Users where e.userID == UserEntity.userID select e;
        var delete = del.Count();

        Assert.AreEqual(0, delete);

    }

我做了一个查询并检查了userID及其内容是否被删除。我在控制器中没有改变任何内容。