Callum Linington Callum Linington - 1 month ago 7
C# Question

Why do I get a NullReferenceException in this MSpec test?

So I have these nuget packages installed:

Nuget

Culminating in these references:

References

I use NCrunch. I have this spec:

namespace GlobPatternMatching.Tests
{
using FluentAssertions;

using Machine.Fakes;
using Machine.Specifications;

[Subject(typeof(GlobMatching))]
public class When_Given_Literal : WithSubject<GlobMatching>
{
private static string pattern = "path";

private static string[] result;

private Establish context => () =>
{
pattern = "path";
};

private Because of => () => result = Subject.GetGlobs(pattern);

private It should_return_path_in_the_array = () =>
{
result[0].Should().Be("path");
};
}
}


For this class:

namespace GlobPatternMatching
{
using System;

public class GlobMatching
{
public string[] GetGlobs(string pattern)
{
return pattern.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}


TDD'ing straight up, I get null reference exception. When I debug I can't step through the method, and all the spec class fields are null.....

I don't feel like I'm missing anything, but if you don't mind having a look and figuring what I've done wrong here that would be good. I'm using latest VS2015, NCrunch etc...

Answer

You wouldn't believe what the issue was...

private Establish context => () =>
{
    pattern = "path";
};

private Because of => () => result = Subject.GetGlobs(pattern);

I've put => instead of =....

// ----------------------\/-------
private Establish context = () =>
{
    pattern = "path";
};

// ----------------\/------------    
private Because of = () => result = Subject.GetGlobs(pattern);