当我执行Text到存储库层时,但是之后尝试执行通用存储库的FindAsync方法时,它无法检索记录。
当我使用存储库层来使用以下方法测试FindAsync方法时,它是有效的:
using System.Linq;
using System.Threading.Tasks;
using Xunit;
public class EmailTemplateUnitTest
{
[Fact]
public void GetEmailTemplate_Repository_Layer()
{
var emailTemplate = new EmailTemplate();
var context = GetDbContext();
var result = new EmailTemplateRepository(context).getEmailTemplateByName("forgotpassword");
var emailTemplateId = result.Result.EmailTemplateId;
Assert.Equal(1, result.Result.EmailTemplateId);
}
public NotificationContext GetDbContext()
{
var builder = new DbContextOptionsBuilder<NotificationContext>();
builder.UseSqlServer("Data Source=solodev.database.windows.net;
Initial Catalog=DatabaseName;User ID=user; Password=Password");
var dbContext = new NotificationContext(builder.Options);
dbContext.Database.EnsureCreated();
return dbContext;
}
}
存储库方法:
public class EmailTemplateRepository : GenericRepository<EmailTemplate>, IEmailTemplateRepository
{
private readonly NotificationContext _notificationContext;
public EmailTemplateRepository(NotificationContext repositoryContext)
: base(repositoryContext)
{
_notificationContext = repositoryContext;
}
public async Task<EmailTemplate> getEmailTemplateByName(string Name)
{
try
{
var templateDate = await FindAsync(e => e.MailFor == Name);
return templateDate;
}
catch (Exception ex)
{
throw;
}
}
}
通用存储库方法:
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
protected GenericDataContext _context;
public virtual async Task<T> FindAsync(Expression<Func<T, bool>> match)
{
try
{
return await _context.Set<T>().SingleOrDefaultAsync(match);
}
catch (Exception ex)
{
throw;
}
}
}
public class GenericDataContext : DbContext
{
public GenericDataContext(DbContextOptions<GenericDataContext> options) : base(options) { }
protected GenericDataContext(DbContextOptions options) : base(options) { }
}
上面的代码有效,但 当我尝试使用服务层进行单元测试时, 通用存储库的方法给出空记录。
服务层方法:
public class EmailTemplateUnitTest
{
[Fact]
public void GetEmailTemplate_Service_Layer_By_Mock()
{
var emailTemplate = new EmailTemplate();
var productRepositoryMock = new Mock<IGenericRepository<EmailTemplate>>();
var unitOfWorkMock = new Mock<EmailTemplateRepository>(GetDbContext());
IEmailTemplateService sut = new EmailTemplateService(unitOfWorkMock.Object);
var actual = sut.getEmailTemplateByName("forgotpassword");
Assert.NotNull(actual);//assert that a result was returned
Assert.Equal(1, actual.Result.ResponseInfo.EmailTemplateId);
}
}
在我的sql数据库中,EmailTemplate表的EmailTemplateId列的值为1,因此在执行方法时,EmailTemplateId的预期结果应为1。