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

Moq and setting up DB Context

我有一个 Entity Framework 数据库上下文文件。 我正在尝试在 NUnit 中设置 Moq 框架。当前在 Moq Nunit 测试中收到以下错误。我将如何设置 DBContext,并将项目添加到产品 Table?

"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 class 来指定您想要使用内存数据库来 运行 您的测试。

[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 中提供的连接字符串未用作测试的一部分。

可以找到更多信息here