这是存储库类
using System;
using System.Collections.Generic;
using Dealer.Rails.Common.Utils;
using Dealer.Rails.Repository.Entities.C3;
using Dealer.Rails.Repository.Repositories.C3.Interfaces;
using Dealer.Rails.Repository.Repositories.Soar;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Dealer.Rails.Repository.Repositories.C3
{
public class VehicleStagingRepository : BaseRepository, IVehicleStagingRepository
{
public VehicleStagingRepository(ILogger<VehicleStagingRepository> logger)
: base(logger)
{
}
public void SaveVehicleStaging(List<ImportStageVh> vehicleStagingRecords, C3Context c3Context)
{
using (var transaction = c3Context.Database.BeginTransaction())
{
var vehicleStagingRecordBeforeSaving = new ImportStageVh();
try
{
foreach (var vehicleStagingRecord in vehicleStagingRecords)
{
vehicleStagingRecordBeforeSaving = vehicleStagingRecord;
c3Context.ImportStageVh.Add(vehicleStagingRecord);
c3Context.SaveChanges();
}
}
catch (TimeoutException tex)
{
transaction.Rollback();
_logger.LogError(LoggingEvents.SaveEmployeeStaging, tex.Message);
throw;
}
catch (Exception ex)
{
transaction.Rollback();
_logger.LogError(LoggingEvents.SaveEmployeeStaging, ex, JsonConvert.SerializeObject(vehicleStagingRecordBeforeSaving));
throw new Exception(vehicleStagingRecordBeforeSaving.ToString(),ex);
}
transaction.Commit();
}
}
}
}
这是使用MOQ的Xunit测试用例。
using Dealer.Rails.Repository.Entities.C3;
using Dealer.Rails.Repository.Repositories.C3;
using Dealer.Rails.Repository.Repositories.C3.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using System.Collections.Generic;
using Xunit;
namespace Dealer.Rails.Repository.Tests.Repositories.Rails
{
public class VehicleStagingRepositoryTests
{
[Fact]
[Trait("Repositories", "C3")]
public void Should_Dump_Records_To_Vehicle_Staging_Dump()
{
// Arrange
var optionsBuilder = new DbContextOptionsBuilder<C3Context>();
optionsBuilder.UseSqlServer("Data Source=dev.c3.dealertrack.corp;Initial Catalog=c3_bmc;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
var mockLogger = new Mock<ILogger<VehicleStagingRepository>>();
var mockC3Context = new C3Context(optionsBuilder.Options);
// var vehicleStagingRecords = new List<ImportStageVh>();
var mockRepository = new Mock<IVehicleStagingRepository>();
mockRepository.Setup(x => x.SaveVehicleStaging(It.IsAny<List<ImportStageVh>>(), mockC3Context));
// System under test is TemplateColumnRepository
var sut = new VehicleStagingRepository(mockLogger.Object);
// Act
sut.SaveVehicleStaging(new List<ImportStageVh>(), mockC3Context);
// Assert
mockRepository.Verify();
// mockRepository.Verify(m=>m.SaveVehicleStaging(vehicleStagingRecords,mockC3Context),Times.Once,"Failed to call SaveVehicleStaging method");
}
}
}
MOQ应该允许我独立测试存储库。我面临的问题是