最小起订量并设置数据库上下文

最小起订量并设置数据库上下文

问题描述:

我有一个Entity Framework DB Context文件. 我正在尝试在NUnit中设置Moq框架. Moq Nunit测试目前收到以下错误.我将如何设置DBContext,并将项目添加到产品表中?

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 DBContext, and add items to a Product Table?

尚未为此DbContext配置任何数据库提供程序.可以通过重写DbContext.OnConfiguring方法或通过在应用程序服务提供程序上使用AddDbContext来配置提供程序.如果使用了AddDbContext,那么还请确保您的DbContext类型接受DbContextOptions对象在其构造函数中,并将其传递给DbContext的基本构造函数."

"No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext."

电子数据库上下文文件

public partial class ElectronicsContext : DbContext
{
    public ElectronicsContext()
    {
    }

    public ElectronicsContext(DbContextOptions<ElectronicsContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Product> Product { get; set; }
    public virtual DbSet<ProductCategory> ProductCategory { get; set; }

Startup.cs

    var connection = @"Server=localhost;Database=Electronics;Trusted_Connection=True;ConnectRetryCount=0";
    services.AddDbContext<ElectronicsContext>(options => options.UseSqlServer(connection));

Moq Nunit测试

 [SetUp]
 public void Setup()
 {
    var ElectronicsContext = new Mock<ElectronicsContext>();
    var ProductRepository = new Mock<ProductRepository>();

    Product producttest = new Product();
    _dbContext.Product.Add(new Product {ProductId = 1, ProductName = "TV", ProductDescription = "TV testing",ImageLocation = "test"});
    _dbContext.SaveChanges();

您无需在单元测试中模拟上下文.您应该使用DbContextOptions类来指定要使用内存数据库来运行测试.

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

    }
}

这与数据库的内存表示形式有关,而不是依赖于物理服务器.您在startup.cs中提供的连接字符串不用作测试的一部分.

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.

可以在此处找到更多信息