【发布时间】:2019-04-09 23:48:55
【问题描述】:
.Net Core 2.2 / EFC 2.2.3 / Pomelo.EntityFrameworkCore.MySql 2.2.0
假设您有一个名为 Colors 的表,其中包含一些预定义的数据。
public void Configure(EntityTypeBuilder<Color> builder)
{
builder.ToTable("Colors");
builder.HasKey(r => r.Id).UseMySqlIdentityColumn();
builder.Property(r => r.Name).IsRequired().HasMaxLength(255);
builder.Property(v => v.RGB).IsRequired().HasMaxLength(7);
builder.HasData(GetSeed());
}
private ICollection<Color> GetSeed()
{
return new List<Color>()
{
new Color(){Id=1, Name="Black", RGB="#000"},
new Color(){Id=2, Name="White", RGB="#fff"},
}
}
我的一项测试是测试 CreateColorCommandHandler。很直接
var Context = CBERPContextFactory.Create();
var query = new CreateColorCommandHandler(Context);
var command = new CreateColorCommand();
command.Name= "Random color";
command.RGB = "#001122";
var colorId = await query.Handle(command, CancellationToken.None);
//Assert
Assert.IsInstanceOf<long>(colorId);
Assert.NotZero(colorId);
var cor = Context.Colors.Where(p => p.Id == colorId).SingleOrDefault();
Assert.NotNull(cor);
Assert.AreEqual(command.Name, cor.Name);
Assert.AreEqual(command.RGB, cor.RGB);
CBERPContextFactory.Destroy(Context);
//>>> Handle simply add a new entity without informing ID
处理方法
public async Task<long> Handle(CreateColorCommand request, CancellationToken cancellationToken)
{
var entity = new Color
{
Name = request.Name,
RGB = request.RGB,
};
_context.Colors.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
当我运行这个测试时,我得到了错误An item with the same key has already been added. Key: 1。这意味着 InMemoryDatabase 没有自动增量功能。
我是不是写错了测试?
如何测试这样的案例?我想确保命令正常。
可能我在这里遗漏了一些非常基本的规则。
【问题讨论】:
-
你能显示
Handle方法吗?您如何将新颜色保存到数据库中? -
请注意,如果其中一个断言失败,
CBERPContextFactory.Destroy(Context);将不会被执行。 -
@Fabio,编辑显示手柄
标签: c# entity-framework unit-testing testing