简体   繁体   中英

System.ArgumentNullException: Value cannot be null

I'm creating a Unit Test for my CRUD and receiving this kind of error in my Delete test method:

System.ArgumentNullException: Value cannot be null.

I checked and found out that whenever I'm running the test, the contents under my userID was already deleted but receiving a "Failed" status in my Test Results bar. Can anyone help me resolve my issue?

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

Here's my code:

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

}

Controller:

[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");
    }

It stops at this line of the controller: db.Users.Remove(user);

I resolved my issue by doing this:

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

    }

I made a query and checked if the userID together with its contents are deleted. I did not change any in my controller.

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