mercredi 24 juin 2015

Why am I getting the following error: "System.NullReferenceException: Object reference not set to an instance of an object." when I run a Unit Test?

I have never run Unit testing before and I am just trying to run an example I have found on the net over and over in regards to the view name.

My Test code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Web.API.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Mvc;
namespace Admin.Web.API.Controllers.Tests
{
    [TestClass()]
    public class HomeControllerTests
    {
        [TestMethod()]
        public void IndexTest()
        {
            HomeController controller = new HomeController();
            var result = controller.Index() as ViewResult;
            Assert.AreEqual("Index", result.ViewName);
        }
    }
}

The error I am getting is System.NullReferenceException: Object reference not set to an instance of an object. on the Line that sets the view result.

What do I need to do to get this working? Is there anything out there that is more descriptive as to Unit testing examples?

Edit one

Controller Code for Index

public ActionResult Index()
{
    if (this.Session["UserID"] == null)
    {
        return View("Login");
    }
    else
    {
        ViewBag.Title = "Index";
        ViewBag.SiteID = this.Session["SiteID"];
        ViewBag.AssemblyVersion = this.Session["AssemblyVersion"];
        ViewBag.UserFirstName = this.Session["FirstName"];
        GoogleAnalytics _oGoogleAnalytics = new GoogleAnalytics();
        ViewBag.GoogleAnalytics = _oGoogleAnalytics.GetGoogleAnalytics(
            this.Session["GoogleAnalyticsAccountCode"].ToString(),
            Convert.ToBoolean(this.Session["UseGoogleAnalytics"]));
            return View("Index");
    }
}

Aucun commentaire:

Enregistrer un commentaire