Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!

Null Reference Error When Trying To Unit Test Code Setting

+2 votes

I'm trying to unit test this code:

        public async Task<Messaging.BaseTypes.BaseWidget> GetWidgetAsync(string widgetId)
            var widget = await RetrieveWidget(widgetId, true); //true here fires off other if-else logic for what to do 
                      //with a null widget
            if (widget != null) return widget.Application;
            Response.StatusCode = 404; //this is the line that throws the null reference error. Says Response is not set to 
                //an instance of an object.
            return null;
I can test the happy path and get it to return the widget, but when I try to test the Response.StatusCode line, the code throws a null reference error every time. What am I missing? Here is my test code. 
        [TestMethod, Isolated]
        public void GetWidgetAsync_ShouldReturnNullAndSetResponseStatusCodeTo404_IfWidgetIsNull()
            string widgetId = "12341224-1234-1234-1234-123412341234";
            var controllerUnderTest = Isolate.Fake.Dependencies<Application>();
            var fakeWidget = Isolate.Fake.Instance<WidgetApplication>();
            Isolate.NonPublic.WhenCalled(controllerUnderTest,                        "RetrieveWidget").WillReturn(Task.FromResult(Task.CompletedTask)); //this is how I'm setting the RetrieveWidget call
                //to return null
            var getWidgetAsyncResponse = controllerUnderTest.GetWidgetAsync(appId);
            Isolate.Verify.NonPublic.WasCalled(controllerUnderTest, "RetrieveWidget");
My understanding is when I do this:
    var controllerUnderTest = Isolate.Fake.Dependencies<WidgetApplication>();
it should create all dependencies of the <Widget>
asked Oct 31 by wayne (220 points)

1 Answer

0 votes

When you do:

var controllerUnderTest = Isolate.Fake.Dependencies<WidgetApplication>();

You create a new object "WidgetApplication" and fake all the dependencies that are passed to his c'tor.

So controllerUnderTest is a new WidgetApplication and all of its dependencies are faked.

answered Nov 2 by Raphy (2,070 points)
Thanks for the link, Raphy. If I am understanding the docs correctly, in my tests I will need to instantiate any fake dependencies in that constructor if I want to test them or any methods they have? For example, I would need to add:

var foo = Isolate.GetFake<DependencyOfWidgetApplication>(controllerUnderTest);

If I wanted to be able to do anything with the DependencyOfWidgetApplication in my tests?

If that dependency is passed to the constructor then yes, to extract it you'll need GetFake and then it's a fake object.

If the dependency is instantiated within the object you'll need to create a handle for that future object.