machine / machine.specifications

Machine.Specifications is a Context/Specification framework for .NET that removes language noise and simplifies tests.
MIT License
885 stars 178 forks source link

What is the difference between Establish context = Things and Establish context = () => Things() #458

Closed mikeblakeuk closed 2 years ago

mikeblakeuk commented 2 years ago

In MSpec, does it make a difference if you do Establish context = Things vs Establish context = () => Things() ?

[ReSharper suggestion]

robertcoltheart commented 2 years ago

Readability and consistency, mostly. It's up to you how you organize your tests, though I'd suggest keeping each context/spec as self-contained as possible. The lambda notation (option 2) is more consistent with all your Because and It elements which also use the lambda notation.

mikeblakeuk commented 2 years ago

I agree, we should turn off the R# recommendation image

It was more around the pros and cons of the actual IL. e.g.

 public class MachineSpec
    {
        static string _source;

        static void SharedSetup()
        {
            _source = "a";
        }

        static void ShouldEqual()
        {
            _source.ShouldEqual("a");
        }

        public class when_method_group
        {
            Establish ctx = SharedSetup;
            It should_parse_the_environment = ShouldEqual;
        }

        public class when_method_lambda
        {
            Establish ctx = () => SharedSetup();
            It should_parse_the_environment = () => ShouldEqual();
        }

        public class when_delegate
        {
            Establish ctx = delegate() { SharedSetup(); };
            It should_parse_the_environment = delegate() { ShouldEqual(); };
        }
    }

Becomes:

public class MachineSpec
  {
    private static string _source;

    private static void SharedSetup() => MachineSpec._source = "a";

    private static void ShouldEqual() => MachineSpec._source.ShouldEqual<string>("a");

    public class when_method_group
    {
      private Establish ctx = new Establish(MachineSpec.SharedSetup);
      private It should_parse_the_environment = new It(MachineSpec.ShouldEqual);
    }

    public class when_method_lambda
    {
      private Establish ctx = (Establish) (() => MachineSpec.SharedSetup());
      private It should_parse_the_environment = (It) (() => MachineSpec.ShouldEqual());
    }

    public class when_delegate
    {
      private Establish ctx = (Establish) (() => MachineSpec.SharedSetup());
      private It should_parse_the_environment = (It) (() => MachineSpec.ShouldEqual());
    }
  }