Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Delete, record returned even though it is deleted in the DB

I am using Nunit to test a method in my controller which deletes a record from the DB. Everything works correctly and the record is deleted when I check but somehow

db.AssesorMaxProjectLoad.Find(previousLoad.ID) 

still returns the deleted value and makes my test fail.

Test:

[Test]
public void AssesorMaxProjectLoadsDeleteLoad()
{
   var previousLoad = db.AssesorMaxProjectLoad.Where(t => t.AssesorID == testAssesor3ID).FirstOrDefault(t => t.TaskGroupID == taskGroupID);
   var result = controller.DeleteConfirmed(previousLoad.ID) as ViewResultBase;
   var newProjectLoad = db.AssesorMaxProjectLoad.Find(previousLoad.ID).MaxAssignedProjectLoad;
   Assert.AreEqual(null, newProjectLoad);
}

Controller Method its Testing:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
   AssesorMaxProjectLoad assesorMaxProjectLoad = db.AssesorMaxProjectLoad.Find(id);
   db.AssesorMaxProjectLoad.Remove(assesorMaxProjectLoad);
   db.SaveChanges();
   return RedirectToAction("Index", "AssesorMaxProjectLoads", new { id = assesorMaxProjectLoad.TaskGroupID });
}

Whats going on or what am I missing? I don't understand how it can be returned when it is no longer in the database?

like image 683
Spitfire5793 Avatar asked Sep 02 '25 09:09

Spitfire5793


1 Answers

It's because the DbContext in your unit test is disconnected from the DbContext in your controller method.

What's happening if you have two instances of DbContext. When you delete a record in the database, that change is not promulgated to the other context and so when you do a find for your record, the unit test context doesn't know anything has changed and returns the original value.

You will need to recreate the DbContext in your unit test after you run the controller method to ensure you are looking at the latest data.

Alternatively, look into mocking the DbContext calls entirely.

like image 109
Steve Avatar answered Sep 04 '25 21:09

Steve