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

使用NetArchTest进行架构测试时,密封类规则断言出现误判

问题:NetArchTest断言Request类为sealed但未标记的类测试仍通过

我正在使用NetArchTest编写架构适配测试,尝试断言所有Request类均为sealed,但测试代码如下:

[Fact]
public void Should_Have_Request_To_Be_Sealed()
{
    var result =
        Types.InAssembly(typeof(ApplicationServiceRegistration).Assembly)
            .That()
            .AreClasses()
            .And()
            .Inherit(typeof(IRequest))
            .Should()
            .BeSealed()
            .GetResult();

    Assert.True(result.IsSuccessful);
}

我的Request类示例并未标记为sealed:

public class CreateCategoryCommand : IRequest<Result<CategoryDto, BaseError>>
{
    public string Name { get; set; } = string.Empty;
    public string? Code { get; set; }
}

public class CreateClientCommand : IRequest<Result<ClientDto, BaseError>>
{
    public string Name { get; set; } = string.Empty;
}

但测试仍通过了,请问问题出在哪里?


原因分析

问题出在Inherit(typeof(IRequest))这个筛选条件上:

  • NetArchTest中的Inherit()方法仅针对类的继承关系,即检查类是否继承自某个基类。
  • 你的Request类是实现IRequest接口,并非继承该接口,所以这个筛选条件没有匹配到任何类。
  • 当没有符合条件的类时,NetArchTest的断言会默认视为“成功”(因为没有违反规则的对象),所以测试会通过。

解决方案

将筛选条件从Inherit(typeof(IRequest))改为ImplementInterface(typeof(IRequest)),因为接口的实现需要用这个方法来匹配:

[Fact]
public void Should_Have_Request_To_Be_Sealed()
{
    var result =
        Types.InAssembly(typeof(ApplicationServiceRegistration).Assembly)
            .That()
            .AreClasses()
            .And()
            .ImplementInterface(typeof(IRequest))
            .Should()
            .BeSealed()
            .GetResult();

    Assert.True(result.IsSuccessful);
}

修改后运行测试,会发现测试失败(符合预期,因为你的Request类未标记sealed),此时给Request类加上sealed修饰符,测试即可通过:

public sealed class CreateCategoryCommand : IRequest<Result<CategoryDto, BaseError>>
{
    // ...
}

public sealed class CreateClientCommand : IRequest<Result<ClientDto, BaseError>>
{
    // ...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:01:07