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

单元测试方法未执行求助:AccountTypeTests测试类异常排查

测试方法无法执行的排查与解决

我有如下测试类:

[TestClass]
public class AccountTypeTests
{       
    private AccountTypeService _accountTypeService;

    [TestInitialize]
    private void Initialize ()
    {
        var options = new DbContextOptionsBuilder<AccountingDBContext>()
                    .UseInMemoryDatabase(databaseName: "InMemoryDatabase")
                    .Options;
        var mock=new Mock<IDbContextFactory<AccountingDBContext>>();
        mock.Setup(p => p.CreateDbContext()).Returns(() => new AccountingDBContext(options));
         
        _accountTypeService = new AccountTypeService(mock.Object);
    }

    [TestMethod]
    public void AccountTypeIsCreatedWhenGuidIsValid()
    {
    }
}

之后修改为如下写法:

private AccountTypeService _accountTypeService;

private AccountTypeService Initialize ()
{
    var options = new DbContextOptionsBuilder<AccountingDBContext>()
                .UseInMemoryDatabase(databaseName: "InMemoryDatabase")
                .Options;
    var mock=new Mock<IDbContextFactory<AccountingDBContext>>();
    mock.Setup(p => p.CreateDbContext()).Returns(() => new AccountingDBContext(options));
     
    return _accountTypeService = new AccountTypeService(mock.Object);
}

[TestMethod]
public void AccountTypeIsCreatedWhenGuidIsValid()
{
    //Arrange
    AccountTypeService _accountTypeService=Initialize();
}

两种写法均无编译报错,但测试方法始终无法执行,尝试将工厂注入构造函数后问题依旧,求解决办法。


排查与解决步骤

  • 恢复测试类的[TestClass]特性
    第二种写法里的测试类丢失了[TestClass]标记,这是MS Test框架识别测试类的必要条件,没有它测试运行器根本不会扫描到类中的测试方法。必须把特性加回类定义:

    [TestClass]
    public class AccountTypeTests
    {
        // 类内代码...
    }
    
  • 确认测试方法的访问修饰符
    确保带[TestMethod]标记的方法是public权限,若误改为private,测试框架会直接忽略该方法。

  • 清理并重新生成解决方案
    编译缓存可能导致测试运行器无法识别最新代码,右键解决方案选择「清理解决方案」,再执行「重新生成解决方案」,之后重新运行测试。

  • 核对测试运行器框架
    如果你用Visual Studio,确认测试资源管理器选择的是MS Test框架(你的代码用的是MS Test的特性),而非xUnit或NUnit,选错框架会导致测试无法被识别。

  • 检查项目依赖完整性
    确认测试项目已正确引用Microsoft.VisualStudio.TestTools.UnitTesting、Moq以及业务逻辑项目,缺失核心依赖会导致测试无法加载执行。

  • 规避内存数据库命名冲突(可选)
    虽然这不是测试无法执行的直接原因,但相同数据库名可能引发后续测试的数据污染。可以给每个测试生成唯一数据库名:

    .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:04:53