Autofac无法与.Include(...)一起使用的mocking。
创始人
2024-11-12 12:00:40
0

这个问题是因为使用了Autofac的Mocks自动解决依赖项功能,但是.Include(...)方法会跳过Mocks,并导致无法正确设置DbContext,从而引发错误。解决这个问题的方法是手动模拟实体集,并使用Moq框架模拟实体集的.Include(...)方法。以下是一个示例:

// 定义一个IQueryable集合的接口,用于后续的模拟。
public interface IQueryableSet : IDbSet, IQueryable where T : class
{
}

// 在测试类的构造函数中手动创建实体集对象并模拟.Include(...)方法。
[TestFixture]
public class MyTests
{
    private Mock> _mockSet;
    private Mock _mockContext;
    private MyRepository _repo;

    public MyTests()
    {
        var data = new List
        {
            new MyEntity { Id = 1, Name = "Entity 1" },
            new MyEntity { Id = 2, Name = "Entity 2" },
            new MyEntity { Id = 3, Name = "Entity 3" }
        }.AsQueryable();

        _mockSet = new Mock>();
        _mockSet.As>().Setup(m => m.Provider).Returns(data.Provider);
        _mockSet.As>().Setup(m => m.Expression).Returns(data.Expression);
        _mockSet.As>().Setup(m => m.ElementType).Returns(data.ElementType);
        _mockSet.As>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        _mockContext = new Mock();
        _mockContext.Setup(c => c.MyEntities).Returns(_mockSet.Object);

        _repo = new MyRepository(_mockContext.Object);
    }

    // 测试可以使用模拟集合,并测试.Include(...)方法可以正确地作用于模拟。
    [Test]
    public void MyTest()
    {
        var entities = _repo.GetEntitiesWithChildren();
        Assert.AreEqual(3, entities.Count());
        _mockSet.Verify(m => m.Include(It.IsAny()), Times.Once());
    }
}

相关内容

热门资讯

wpk模拟器多开!hhpoke... wpk模拟器多开!hhpoker的辅助是真的吗(透视)攻略-好像解谜存在有挂hhpoker的辅助是真...
透视普及!aapoker脚本(... 透视普及!aapoker脚本(透视)德州透视hhpoker,教程窍门(揭秘有挂)-哔哩哔哩1、起透看...
透视曝光!hhpoker视频巡... 透视曝光!hhpoker视频巡查真的假的(透视)hhpoker软件安装包,教程指南书(确实有挂)-哔...
pokemmo脚本辅助器!we... pokemmo脚本辅助器!wepoker怎么下载游戏(透视)技巧-一贯专业有挂小薇(辅助器软件下载)...
wepoker好友局透视!德普... wepoker好友局透视!德普之星辅助器(透视)插件-本来开挂有挂1、wepoker好友局透视免费辅...
哈糖大菠萝开挂!aa poke... 您好,哈糖大菠萝开挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家...
透视详细!智星德州可以透视吗(... 透视详细!智星德州可以透视吗(透视)poker红龙辅助,教程经验(有挂细节)-哔哩哔哩1、实时智星德...
淘宝买wepoker透视有用吗... 淘宝买wepoker透视有用吗!hhpoker辅助(透视)方法-总是揭露存在有挂1、金币登录送、破产...
透视详情!wpk透视辅助下载(... 透视详情!wpk透视辅助下载(透视)智星菠萝透视,教程大纲(有挂细节)-哔哩哔哩1、wpk透视辅助下...
wepoker祈福有用吗!hh... wepoker祈福有用吗!hhpoker怎么防透视(透视)教程-一贯揭幕有挂hhpoker怎么防透视...