Xunit - 如何将Moq和EF Core用于身份主键

时间:2017-04-04 13:05:56

标签: c# moq entity-framework-core xunit

我正在尝试使用AutoMoq和Xunit for Inserting功能自动化我的UnitTesting。

但我一直认为我无法在KeyColumn中插入一个值,如下所示。 EnrolmentRecordID是我的SQL数据库中的IdentityColumn,其值在插入时自动生成。

  

消息:Microsoft.EntityFrameworkCore.DbUpdateException:错误   更新条目时发生。查看内部异常   细节。   ---- System.Data.SqlClient.SqlException:当IDENTITY_INSERT为'时,无法在表'EN_Schedules'中为identity列插入显式值   设置为OFF。

如果我不使用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);
    }
}

您能否帮助我如何使用Moq生成MockObject并测试Add服务?感谢。

1 个答案:

答案 0 :(得分:1)

这个简化的例子说明了如何将测试对象与具体结构分离,以便可以单独进行单元测试。

摘要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));
}

确保实现包装实际上下文并提供所需的功能。

主题类是否取决​​于抽象。

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();
    }
}

有了这个,测试对象的依赖关系可以被模拟并用于测试。

[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);
}