Nancy: NullReferenceException when testing with context factory.

Created on 28 Aug 2015  路  3Comments  路  Source: NancyFx/Nancy

My test code:

var browser = new Browser(
    with =>
        {
            with.Module<PatientSearchModule>();
            with.Dependencies(patientSearchService, mappingEngine);
            with.ContextFactory(new TestingContextFactory());
        });
browser.Get("/test", with => with.HttpRequest());

My test context factory is this:

public class TestingContextFactory : INancyContextFactory
    {
        public NancyContext Create(Request request)
        {
            return new NancyContext();
        }
    }

I am getting the following exception:

Object reference not set to an instance of an object.
   at Nancy.Conventions.StaticContentConventionBuilder.<>c__DisplayClass2.<AddDirectory>b__0(NancyContext聽ctx,聽String聽root)
   at Nancy.DefaultStaticContentProvider.GetContent(NancyContext聽context)
   at Nancy.NancyEngine.HandleRequest(Request聽request,聽Func`2聽preRequest,聽CancellationToken聽cancellationToken)
   at Nancy.NancyEngineExtensions.HandleRequest(INancyEngine聽nancyEngine,聽Request聽request,聽Func`2聽preRequest)
   at Nancy.Testing.Browser.HandleRequest(String聽method,聽Url聽url,聽Action`1聽browserContext)
   at Nancy.Testing.Browser.HandleRequest(String聽method,聽String聽path,聽Action`1聽browserContext)

Now, I understand that I might be doing something wrong. But a null ref isn't be the error that will help me know what to do to fix my code.

Bug Up for Grabs

All 3 comments

The implementation is clearly breaking the "contract" of the INancyContextFactory which requires the implementation to fully populate the returned NancyContext, which includes at least passing it the given request. I agree that the API should've enforced it better though. Preferably through the NancyContext ctor.

Not passing the request yields a null reference at https://github.com/NancyFx/Nancy/blob/7bdfb4f22d8a717a461237342e9d39044c2fb5c4/src/Nancy/Conventions/StaticContentConventionBuilder.cs#L41

I'm really not sure what we can do to protect against this though. Yes, in this case we can force the request being set by adding it as a parameter to the NancyContext ctor (which would be a major breaking change at this point), but what this boils down to is simply _always_ checking _everything_, for a null reference, _everywhere_. At the end of the day, it's impossible to "protect" the users from themselves :wink:

@khellang What do you think of that patch?

Was this page helpful?
0 / 5 - 0 ratings