我正在尝试使用AutoMoq和Xunit插入特性来自动化UnitTesting。Xunit - 如何使用Moq和EF Core作为标识主键
但我一直得到,我不能插入一个值到KeyColumn作为以下。 EnrolmentRecordID
是我的SQL数据库中的IdentityColumn,它的值是在插入时自动生成的。
消息:Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误 。请参阅 的内部例外详情。 ---- System.Data.SqlClient.SqlException:当IDENTITY_INSERT为 设置为OFF时,无法在表'EN_Schedules'中插入标识列的显式值。
这可以避免,如果我不使用Moq或我不设置数据到EnrolmentRecordID
列。但我不知道如何排除AutoMoq中的EnrolmentRecordID
。由于它是关键列,因此我无法将NULLABLE功能设置为该列。
StudentSchedule.cs
public class StudentSchedule
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EnrolmentRecordID { get; set; }
public string AcademicYearID { get; set; }
[Display(Name = "Student")]
public string StudentName { get; set; }
public string ProposedQual { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? DateCreated { get; set; }
}
AddService
public async Task Add(StudentSchedule model)
{
await _context.Schedules.AddAsync(model);
await _context.SaveChangesAsync();
}
XUnitTest
public class TestCommandsSchedule
{
private ERAppData.Commands.CommandSchedule _command;
public TestCommandsSchedule()
{
_command = new ERAppData.Commands.CommandSchedule(AppsecDBContext.GenerateAppsecDBContext() as ERAppData.DbContexts.AppsecDbContext);
}
[Theory]
[AutoMoqData]
public async Task Should_Add_Schedule(StudentSchedule model)
{
model.AcademicYearID = "16/17";
model.DateCreated = null;
await _command.Add(model);
Assert.True(model.EnrolmentRecordID > 0);
}
}
你能帮我^ h我可以使用Moq生成MockObject
并测试Add
服务吗?谢谢。
这是一个集成测试吗? – Nkosi
不,单元测试 – TTCG
@Nkosi我不应该在UnitTest中使用真实的数据库吗? – TTCG