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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With