TNG / ArchUnitNET

A C# architecture test library to specify and assert architecture rules in C# for automated testing.
Apache License 2.0
927 stars 61 forks source link

Avoid calling System.String.Substring() #254

Open TorstenM1979 opened 7 months ago

TorstenM1979 commented 7 months ago

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

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

TorstenM1979 commented 7 months ago

Sorry for bad formatting, I don't know how this can happen :-(

ArcadeMode commented 5 months ago

I have little experience with this library but here to try and help

Documentation shows you should call Check(Architecture) instead of Evaluate(Architecture) perhaps that helps?