BenMorris / NetArchTest

A fluent API for .Net that can enforce architectural rules in unit tests.
MIT License
1.36k stars 81 forks source link

OnlyHaveDependenciesOn failed cause by const fields #96

Closed bliet closed 3 years ago

bliet commented 3 years ago

Hello.

Description

We have defined a unit test with net arch test. The OnlyHaveDependenciesOn Method failed when the tested type has a const field. The IsSuccessful Property is false.

Example:

Unfortunately I cannot attach a project file. Here the code.

The test class without any usings and a const field. By removing the "const" the test runs successfully.

public class ClassToTest
    {
        private const string ConstText = "TestTest";
        // private readonly string ReadOnlyText = "TestTest";
    }

NetArchtest:

Policy.Define("ConstTest policies", "Dependency conditions for the ConstTest namespace.")
                .For(Types.InAssembly(typeof(ClassToTest).Assembly))
                .Add(
                    types => types
                        .That().ResideInNamespace("ConstTest")
                        .Should().OnlyHaveDependenciesOn("ConstTest", "System"),
                    "Dependency Contract",
                    "The assembly must not have any dependencies to other assemblies.")
                .Evaluate()
                .ShouldBeValid();

Validation Helper:

internal static class AssertPolicyResults
   {
      internal static void ShouldBeValid(this PolicyResults policyResults)
      {
         policyResults.Results.ForEach(r => r.ShouldBeValid());
      }

      private static void ShouldBeValid(this PolicyResult policyResult)
      {
         string failingTypes = string.Empty;
         if (policyResult.FailingTypes?.Any() == true)
         {
            failingTypes = $" (affected types: {string.Join(",", policyResult.FailingTypes.Select(t => t.Name))})";
         }

         policyResult.IsSuccessful.Should().BeTrue($"{policyResult.Description}{failingTypes}");
      }

      private static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
      {
         foreach (T item in source)
         {
            action(item);
         }
      }
   }

Question

Is this a bug? Why the test failed?

NeVeSpl commented 3 years ago

I am not able to reproduce the problem on the given source code. It would be nice if you could prepare a minimal project on which the problem can be reproduced and publish it on github.

bliet commented 3 years ago

Here is the repo. https://github.com/bliet/NetArchConstTestExample

NeVeSpl commented 3 years ago

And this is why I was unable to reproduce the problem, you are using NetArchTest.Rules v1.3.1, but the current version is v1.3.2 on which problem dose not exist anymore :)

bliet commented 3 years ago

Oh my bad, thanks.