我有以下使用实体框架核心的项目:
我正在学习针对上述每个项目编写单元测试用例。现在我认为针对“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 编写单元测试。
您绝对可以测试您的数据库配置,以便任何更改都不会破坏预期的架构。
在您的测试项目中,您可以创建一个新的 DbContextOptionsBuilder 实例并配置内存数据库。使用选项对象,您可以实例化 DBContext 并运行您认为必要的任何断言。
var options = new DbContextOptionsBuilder<MyContext>().UseInMemoryDatabase(databaseName: "testDB").Options;
MyContext _context = new MyContextContext(options);