Sto cercando di automatizzare il mio UnitTesting con AutoMoq e Xunit per l'inserimento di funzionalità.
Ma continuo a ricevere che non posso inserire un valore nella KeyColumn come segue. EnrolmentRecordID
è IdentityColumn nel mio SQL db e il suo valore viene generato automaticamente all'inserimento.
Messaggio: Microsoft.EntityFrameworkCore.DbUpdateException: si è verificato un errore durante l'aggiornamento delle voci. Vedi l'eccezione interna per i dettagli. ---- System.Data.SqlClient.SqlException: impossibile inserire il valore esplicito per la colonna identity nella tabella 'EN_Schedules' quando IDENTITY_INSERT è impostato su OFF.
Può essere evitato, se non uso Moq o non ho impostato i dati nella colonna EnrolmentRecordID
. Ma non so come escludere EnrolmentRecordID
in AutoMoq. Poiché è la colonna chiave, non posso impostare la funzione NULLABLE anche su quella colonna.
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);
}
}
Potresti per favore aiutarmi come usare Moq per generare MockObject
e testare il servizio Add
? Grazie.
questo esempio semplificato mostra come disaccoppiare il soggetto in prova dalle concrezioni in modo che possa essere isolato unitamente.
DbContext
il DbContext
public interface IStudenScheduleService : IGenericRepository<StudentSchedule> {
}
public interface IGenericRepository<T> {
Task<T> AddAsync(T value, CancellationToken cancellationToken = default(CancellationToken));
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken));
}
assicurandosi che l'implementazione avvolga il contesto reale e fornisca le funzionalità desiderate.
La classe dei soggetti dipende dall'astrazione.
public class CommandSchedule {
private readonly IStudenScheduleService _context;
public CommandSchedule(IStudenScheduleService context) {
this._context = context;
}
public async Task Add(StudentSchedule model) {
await _context.AddAsync(model);
await _context.SaveChangesAsync();
}
}
Con quello sul posto le dipendenze del soggetto in esame possono essere prese in giro e utilizzate nell'esercizio del test.
[Theory]
[AutoMoqData]
public async Task Should_Add_Schedule(StudentSchedule model)
//Arrange
var expectedId = 0;
var expectedDate = DateTime.Now;
var context = new Mock<IStudenScheduleService>();
context.Setup(_ => _.SaveChangesAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(1)
.Callback(() => {
model.EnrolmentRecordID = ++expectedId;
model.DateCreated = expectedDate;
})
.Verifiable();
context.Setup(_ => _.AddAsync(It.IsAny<StudentSchedule>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((StudentSchedule m, CancellationToken t) => m)
.Verifiable();
var _command = new CommandSchedule(context.Object);
model.AcademicYearID = "16/17";
model.DateCreated = null;
//Act
await _command.Add(model);
//Assert
context.Verify();
Assert.AreEqual(expectedId, model.EnrolmentRecordID);
Assert.AreEqual(expectedDate, model.DateCreated);
}