首页 > 解决方案 > 如何在 ArchUnit c# 中检查方法返回类型

问题描述

我需要检查是否只有一个类方法(“ExampleMethod”)返回“ExampleType”。我可以用 C# 中的 ArchUnit 做到这一点吗?

标签: c#.netunit-testingtestingarchunit

解决方案


您不需要使用 ArchUnit - 或者其他任何东西,只需使用 .NET 的内置反射 API:

using System;
using System.Linq;
using System.Reflection;

#if !( XUNIT || MSTEST || NUNIT)
    #error "Specify unit testing framework"
#endif

#if MSTEST
[TestClass]
#elif NUNIT
[TestFixture]
#endif
public class ReflectionTests
{
#if XUNIT
    [Fact]
#elif MSTEST
    [TestMethod]
#elif NUNIT
    [Test]
#endif
    public void MyClass_should_have_only_1_ExampleMethod()
    {
        const BindingFlags BF = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

        MethodInfo mi = typeof(MyClass).GetMethods( BF ).Single( m => m.Name == "ExampleMethod" );

#if XUNIT
        Assert.Equal( expected: typeof(ExampleType), actual: mi.ReturnType );
#elif MSTEST || NUNIT
        Assert.AreEqual( expected: typeof(ExampleType), actual: mi.ReturnType );
#endif
    }
}

推荐阅读