Moq and setting up DB Context

后端 未结 1 1079
自闭症患者
自闭症患者 2020-12-02 02:54

I have an Entity Framework DB Context file. I am trying to setup a Moq framework in NUnit. Currently receiving error below for Moq Nunit test. How would I setup the DBContex

相关标签:
1条回答
  • 2020-12-02 03:34

    You don't need to mock the context in unit tests. You should use the DbContextOptions class to specify you want to use an in memory database to run your tests against.

    [TestMethod]
    public void TestProducts()
    {
        var options = new DbContextOptionsBuilder<ElectronicsContext>()
            .UseInMemoryDatabase(databaseName: "Products Test")
            .Options;
    
        using(var context = new ElectronicsContext(options))
        {
            context.Products.Add(new Product {ProductId = 1, ProductName = "TV", ProductDescription = "TV testing",ImageLocation = "test"});
            context.SaveChanges();
        }
    
        using(var context = new ElectronicsContext(options))
        {
            // run your test here
    
        }
    }
    

    This runs against the in-memory representation of your database instead of relying on the physical server. The connection string you provided in the startup.cs is not used as part of the tests.

    More info can be found here

    0 讨论(0)
提交回复
热议问题