Home > Enterprise >  How to check Methods return type in ArchUnit c#
How to check Methods return type in ArchUnit c#

Time:10-29

I need to check that there is only one class method ("ExampleMethod") that returns "ExpamleType". Can I do this with ArchUnit in C #?

CodePudding user response:

You don't need to use ArchUnit - or anything really, just use .NET's built-in reflection 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
    }
}
  • Related