rey*_*123 3 c# unit-testing moq
我目前正在尝试最小化我的Cafe Get方法,ArgumentNullexception如果找不到咖啡馆 ID ,它将抛出一个。
System.NotSupportedException:不支持的表达式:x => x.Cafe 不可覆盖成员(此处:Context.get_Cafe)不能用于设置/验证表达式。
这是因为 moq 无法处理设置表达式之一吗?
[Fact]
public async Task GetCafeByIdAsync_Should_Throw_ArgumentNullException()
{
var cafe = new List<Cafe>()
{
new Cafe { Name = "Hanna", CafeId = 1},
new Cafe { Name = "Bella", CafeId = 2 }
}.AsQueryable();
var mockSet = new Mock<DbSet<Cafe>>();
mockSet.As<IQueryable<Cafe>>().Setup(m => m.Provider).Returns(cafe.Provider);
mockSet.As<IQueryable<Cafe>>().Setup(m => m.Expression).Returns(cafe.Expression);
mockSet.As<IQueryable<Cafe>>().Setup(m => m.ElementType).Returns(cafe.ElementType);
mockSet.As<IQueryable<Cafe>>().Setup(m => m.GetEnumerator()).Returns(cafe.GetEnumerator());
var mapper = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfile());
}).CreateMapper();
var contextMock = new Mock<Context>();
contextMock.Setup(x => x.Cafe).Returns(mockSet.Object); //failing here
var cafeService = new CafeService(contextMock.Object, mapper);
await Assert.ThrowsAsync<ArgumentNullException>(() => cafeService.Get(2));
}
Run Code Online (Sandbox Code Playgroud)
public async Task<VersionResponse> Get(int cafeId)
{
var cafe = await _context.Cafe.Where(w => w.CafeId == cafeId).ToResponse().FirstOrDefaultAsync();
return new VersionResponse()
{
Data = cafe
};
}
Run Code Online (Sandbox Code Playgroud)
Moq 依赖于能够创建覆盖属性的代理类。在Context.Cafe不能被重写。尝试声明该属性virtual。
public virtual IDbSet<Cafe> Cafe { get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6772 次 |
| 最近记录: |