Search code examples
c#nunitin-memory-database

NUnit test fails because object is already in memory


I am trying to run several unit tests (by pressing Run All in Visual Studio). When I run all using Test>Run>All Tests the test below fails, but when I run the individual test (by right clicking the test itself in test Explorer) it succeeds. I believe I have my Setup and TearDown configured wrong, but I'm not sure whats missing.

Error:

Message: System.ArgumentException : An item with the same key has already been added. Key: System.Object[]

My Code:

[TestFixture]
public class GCLandingUserModelTest
{
    DbContextOptions<GreenCardContext> gcopt = new DbContextOptionsBuilder<GreenCardContext>()
        .UseInMemoryDatabase(databaseName: "GreenCardSite").Options;

    private GreenCardContext _mockGC;

    [SetUp]
    public void InitData()
    {
        _mockGC = new GreenCardContext(gcopt);
    }

    [TearDown]
    public void ClearData()
    {
        _mockGC = null;
    }

    [Test]
    public void TestAddObjMoq()
    {
            // Insert seed data into the database using one instance of the context
            _mockGC.UserRolePrice.Add(new UserRolePrice { LGID = 1, UserRoleId = -1 });
            _mockGC.SaveChanges();
            Assert.AreEqual(1, _mockGC.UserRolePrice.ToList().Count, $"UserRolePrice not added to context");

            //verify that obj created and changes were saved on the Mock Context
            int objlgid = _mockGC.UserRolePrice.Where(x => x.UserRoleId == -1).Select(x => x.LGID).First();
            Assert.AreEqual(1, objlgid,$"The returned lgid was: {objlgid}");
    }
}

Solution

  • Maybe you need to clear the in-memory datastore.

    _mockGC.Database.EnsureDeleted();
    

    DatabaseFacade.EnsureDeleted Method

    Ensures that the database for the context does not exist. If it does not exist, no action is taken. If it does exist then the database is deleted.

    Warning: The entire database is deleted, and no effort is made to remove just the database objects that are used by the model for this context.