Questieme
Questieme

Reputation: 993

Dealing with TempData variables in Unit Tests

Following the example from here:

Mocking a TempData in ASP.NET Core in MSTest,

I wrote down the following TestMethod:

[Fact]
public void TestBackMethod()
{
    var httpContext = new DefaultHttpContext();
    var tempData = new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>());
    tempData["id"] = 3008;
    var controller = new PhaseController(Configuration)
    {
        TempData = tempData
    }; 
    var result = controller.Back() as ViewResult;
    Assert.Contains("Index", result.ViewName);
}

For this Controller Method:

public IActionResult Back()
{
    int releaseId = (int)TempData["id"];
    return RedirectToAction("Index", "Phase", new { id = releaseId });
}

However, on this line:

Assert.Contains("Index", result.ViewName);

result is null.

'Object reference not set to an instance of an object.'

Why is this happening and how can I fix it?

Upvotes: 1

Views: 1024

Answers (1)

gunr2171
gunr2171

Reputation: 17520

Because Back doesn't return a ViewResult - it returns a RedirectToActionResult (you can hover over RedirectToAction to see the exact object name). Both of these implement IActionResult.

You get a Null Reference Exception because when you use the as keyword for casting objects it will return null if the conversion is not possible.

If you instead had

var result = (ViewResult)controller.Back();

You would get a difference exception during run time of that line saying the conversion was not possible.

You should do the conversion doing one of these methods:

var result = (RedirectToActionResult)controller.Back();

or

var result = controller.Back() as RedirectToActionResult;

Upvotes: 3

Related Questions