如何在C#中使用ArchUnit校验指定方法的返回类型
校验需求实现结论
完全可以通过C#版ArchUnit(ArchUnit.NET)实现你提出的校验需求。
实现逻辑说明
你需要的「仅名称为ExampleMethod的类方法返回类型为ExampleType」的校验可以拆为两条互斥的规则共同实现:
- 所有名为
ExampleMethod的方法,必须返回ExampleType类型 - 所有名称不是
ExampleMethod的方法,禁止返回ExampleType类型
代码实现示例
首先安装所需NuGet包:ArchUnitNET,如果搭配单元测试框架使用,可额外安装对应适配包,如ArchUnitNET.xUnit(适配xUnit)、ArchUnitNET.NUnit(适配NUnit)。
以下为xUnit框架下的完整校验代码:
using ArchUnitNET.Domain; using ArchUnitNET.Loader; using ArchUnitNET.Fluent; using Xunit; // 引入你业务项目的命名空间 using YourBusinessNamespace; public class MethodReturnTypeArchTest { // 加载待校验的业务程序集 private static readonly Architecture _targetArchitecture = new ArchLoader() .LoadAssemblies(typeof(YourBusinessClass).Assembly) .Build(); [Fact] public void OnlyExampleMethodCanReturnExampleType() { // 规则1:ExampleMethod必须返回ExampleType IArchRule exampleMethodReturnTypeRule = ArchRuleDefinition.Methods() .That() .HaveName("ExampleMethod") .Should() .HaveReturnType(typeof(ExampleType)); // 规则2:非ExampleMethod禁止返回ExampleType IArchRule otherMethodForbiddenReturnTypeRule = ArchRuleDefinition.Methods() .That() .DoNotHaveName("ExampleMethod") .Should() .NotHaveReturnType(typeof(ExampleType)); // 执行两条规则校验 exampleMethodReturnTypeRule.Check(_targetArchitecture); otherMethodForbiddenReturnTypeRule.Check(_targetArchitecture); } }
扩展适配说明
如果存在ExampleMethod重载、或者需要限定ExampleMethod所属的类范围,可以在规则的That()条件后追加过滤逻辑,例如:
- 限定仅指定类下的
ExampleMethod:追加.And().AreDeclaredIn(typeof(TargetClass)) - 限定带指定参数的
ExampleMethod重载:追加.And().HaveParameters(typeof(int), typeof(string))
内容的提问来源于stack exchange,提问作者Andrew Mooweek
相关产品推荐
相关产品推荐

