3

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

System.ArgumentNullException: Value cannot be null.

我检查并发现每当我运行测试时,我的用户 ID 下的内容已经被删除,但在我的测试结果栏中收到“失败”状态。谁能帮我解决我的问题?

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);

4

1 回答 1

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);

    }

我进行了查询并检查了用户ID及其内容是否被删除。我没有更改控制器中的任何内容。

于 2012-10-09T06:42:09.183 回答