gpt4 book ai didi

c# - System.NotSupportedException : Unsupported expression: x => x

转载 作者:行者123 更新时间:2023-12-04 12:36:54 29 4
gpt4 key购买 nike

我目前正在尝试最小起订量 Cafe Get将抛出 ArgumentNullexception 的方法如果找不到咖啡馆 ID。
错误

System.NotSupportedException : Unsupported expression: x => x.CafeNon-overridable members (here: Context.get_Cafe) may not be used in setup / verification expressions.


这是因为 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));
}
SUT
public async Task<VersionResponse> Get(int cafeId)
{
var cafe = await _context.Cafe.Where(w => w.CafeId == cafeId).ToResponse().FirstOrDefaultAsync();
return new VersionResponse()
{
Data = cafe
};
}

最佳答案

Moq 依赖于能够创建覆盖属性的代理类。 Context.Cafe不能被覆盖。尝试声明该属性 virtual .

public virtual IDbSet<Cafe> Cafe { get; set; }

关于c# - System.NotSupportedException : Unsupported expression: x => x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63801893/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com