I am trying to automate my UnitTesting with AutoMoq and Xunit for Inserting feature.
But I keep getting that I cannot insert a value into the KeyColumn as the following. EnrolmentRecordID
is the IdentityColumn in my SQL db and its value is generated automatically at the insertion.
Message: Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details. ---- System.Data.SqlClient.SqlException : Cannot insert explicit value for identity column in table 'EN_Schedules' when IDENTITY_INSERT is set to OFF.
It can be avoided, if I don't use Moq or I don't set the data to EnrolmentRecordID
column. But I don't know how to exclude EnrolmentRecordID
in AutoMoq. Since it's the key column, I cannot set the NULLABLE feature to that column too.
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);
}
}
Could you please help me how I could use Moq to generate the MockObject
and test the Add
Service? Thanks.