通过 Fluent API 编写 EF 核心配置的单元测试是什么以及如何编写?

问题描述 投票:0回答:1

我有以下使用实体框架核心的项目:

  1. MyApp.Domain - 它包含与数据库表映射的所有域实体的列表。
  2. MyApp.EFConfiguration- 它通过 Fluent API 包含所有 Ef 核心相关配置。

我正在学习针对上述每个项目编写单元测试用例。现在我认为针对“MyApp.Domain”项目编写单元测试用例没有意义,因为它只包含属性而没有要测试的行为。

我的应用程序域:

public partial class Customer 
 {
    
     public int Id { get; set; }

     public string Username { get; set; }
     
     public string Email { get; set; }

     public string FirstName { get; set; }

     public string LastName { get; set; }
     
     public ICollection<Order> Orders { get;set; }
}

 public partial class Order 
 {
    
     public int Id { get; set; }

     public int CustomerId { get; set; }
     
     public decimal CurrencyRate { get; set; }

     public string ShippingMethod { get; set; }

     public Customer Customer { get; set; };
}
 

MyApp.EF配置:

public class CustomerEntityTypeConfiguration : IEntityTypeConfiguration<Customer>
    {
        public void Configure(EntityTypeBuilder<Customer> builder)
        {
            builder.ToTable("Customer");
            builder.HasKey(c => c.Id);
            builder.Property(c => c.Username).IsRequired().HasMaxLength(255);
            builder.Property(c => c.FirstName).IsRequired().HasMaxLength(255);
            builder.Property(c => c.LastName).IsRequired().HasMaxLength(255);
        }
    }
    
public class OrderEntityTypeConfiguration : IEntityTypeConfiguration<Order>
    {
        public void Configure(EntityTypeBuilder<Order> builder)
        {
            builder.ToTable("Orders");
            builder.HasKey(c => c.Id);
            builder.Property(c => c.CustomerId).IsRequired();
            builder.Property(c => c.CurrencyRate).IsRequired();
            
            builder
                .HasOne(order  => order.Customer)
                .WithMany(customer => customer.Orders)
                .HasForeignKey(order => order.CustomerId)
        }
    }

我的第一个问题是针对我的所有配置编写单元测试是否有意义,例如

CustomerEntityTypeConfiguration
、'
OrderEntityTypeConfiguration
' 以及其他?

如果是,那么我可以对“

Configure
”和
CustomerEntityTypeConfiguration
类中的“
OrderEntityTypeConfiguration
”方法进行什么以及如何进行单元测试?

如果有人可以帮助我提供以上两门课程的单元测试样本,那么我可以为其他人编写。任何帮助将不胜感激。我正在使用 Xunit 编写单元测试。

c# unit-testing entity-framework-core xunit
1个回答
0
投票

您绝对可以测试您的数据库配置,以便任何更改都不会破坏预期的架构。

在您的测试项目中,您可以创建一个新的 DbContextOptionsBuilder 实例并配置内存数据库。使用选项对象,您可以实例化 DBContext 并运行您认为必要的任何断言。

var options = new DbContextOptionsBuilder<MyContext>().UseInMemoryDatabase(databaseName: "testDB").Options;
MyContext _context = new MyContextContext(options);
© www.soinside.com 2019 - 2024. All rights reserved.