You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xunit中Moq传递mock.Object触发MissingMethodException,传Null正常

问题:Moq模拟对象传入构造函数时抛出MissingMethodException异常

尝试用Moq编写Xunit单元测试,被测类CarQueries的构造函数接收CarValueServiceDbContext和IUserGroupQueries两个参数。测试代码中创建了Mock<IUserGroupQueries>实例,但将_userGroupQueries.Object传入CarQueries构造函数时,抛出System.MissingMethodException,提示找不到System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)方法;传递Null时则可正常运行。

被测类代码

private readonly CarValueServiceDbContext _dbContext;
private readonly IUserGroupQueries _userGroupQueries;

public CarQueries(CarValueServiceDbContext dbContext, IUserGroupQueries userGroupQueries)
{
    _dbContext = dbContext;
    _userGroupQueries = userGroupQueries;
}

测试代码

[Fact]
public async Task Get_PassTrue_ExpectedToGetOnlyMappedCars()
{
    using (var dbContext = new CarValueServiceDbContext(_dbContextOptions))
    {
         var _userGroupQueries=new Mock<IUserGroupQueries>();
        await dbContext.Car.AddRangeAsync(new Car { Name = "test", Id = Guid.NewGuid(), Comment = "hjhghfh" },
                                           new Car {Name="Car1",Comment="comments"},
                                           new Car { Name = "Car1", Comment = "comments",Id=Guid.NewGuid() });
        await dbContext.SaveChangesAsync();

        var rslt = new CarQueries(dbContext, _userGroupQueries.Object);
        var testedMethod=rslt.Get();

    }
}

报错信息

System.MissingMethodException : Method not found: 
'System.Reflection.Emit.AssemblyBuilder 
System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, 
System.Reflection.Emit.AssemblyBuilderAccess)'.
原因及解决办法
  • Moq版本与目标框架不兼容:这个错误核心是Moq依赖的动态反射API在当前.NET版本中已被废弃或移除。比如.NET Core/.NET 5+ 中AppDomain.DefineDynamicAssembly不再被支持,而旧版Moq仍在调用该API。解决方式:升级Moq到适配当前.NET版本的最新版(建议Moq 4.16及以上,这类版本对.NET Core/.NET 5+做了适配)。

  • 目标框架与Moq适配性不匹配:如果项目目标框架是.NET Core/.NET 5+,但安装的Moq是针对.NET Framework开发的旧版本,就会出现API找不到的问题。确认项目的目标框架版本(比如.NET 6/7/8),重新安装对应兼容的Moq NuGet包。

  • 依赖包冲突:项目中其他依赖包可能和Moq的动态代码生成逻辑存在冲突,导致无法找到目标方法。可以尝试清理NuGet缓存,重新安装所有依赖包;或者检查项目中反射相关的依赖包,排查版本不兼容问题。

内容的提问来源于stack exchange,提问作者moris62

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:40:07