TorstenM
TorstenM

Reputation: 21

C# Arch Unit - Avoid calling System.String.Substring()

I'm trying to understand how to avoid calling a method like "System.String.Substring()" with ArchUnit framework by TNG.

First I have a simple library Lib with static method:

namespace Lib
{
    public static class Utility
    {
        public static string SubString(string input, int position)
        {
            return input.Substring(position);
        }
    }
}

Second I have an example console project to show what I want exactly:

namespace Prg
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // this usage is fine
            Console.WriteLine(Lib.Utility.SubString("Hello World", 6));

            // this usage should not be possible and should be "reported" by ArchUnit
            Console.WriteLine("Hello World".Substring(6));

            Console.ReadKey();
        }
    }
}

And, I have a simple MS unit test as follows:

using ArchUnitNET.Domain;
using ArchUnitNET.Loader;
using static ArchUnitNET.Fluent.ArchRuleDefinition;

namespace LibTest
{
    [TestClass]
    public class PrgTest
    {
        private static readonly Architecture Architecture = new ArchLoader().LoadAssemblies(System.Reflection.Assembly.Load("Prg")).Build();

        [TestMethod]
        public void TestIndexOf()
        {
            var classesThatCallStringDotSubString = Classes().That().CallAny("System.String.Substring").Should().NotExist();
            var result = classesThatCallStringDotSubString.Evaluate(Architecture).ToList();

            Assert.IsTrue(result[0].Passed);
        }
    }
}

I do something wrong because the test does not fail. Can anyone help? Thanks a lot.

BR Torsten

Upvotes: 1

Views: 81

Answers (0)

Related Questions