Search code examples
asp.net-mvc-3mspecfakeiteasy

MSpec and base class test failure while writing test for Asp.net mvc 3 controller


I am currently writing some MSpec specs for this controller which has already been implemented (yes I know doing it the "wrong" way round).

It is a "simple" problem but I'm not sure what I'm doing wrong and hopefully someone will be able to point the error of my ways.

My Controller's method is as follows:

 public ActionResult Add()
    {
        this.SetPageTitle("Add something");
        return this.View();
    }

The issue I'm having is with

this.SetPageTitle("Add something");

The method is defined in a base class (BaseController) from which the current controller (CompanyHomeController) is defined.

My spec is as follows:

[Subject(typeof(CompanyHomeController))]
public class when_the_company_add_page_is_requested
{
    static string pageTitle;

    static ActionResult result;

    static CompanyHomeController companyHomeController;

    // Arrange
    Establish a_company_home_controller_context = () =>
        {
            var companyDao = A.Fake<ICompanyDao>();
            companyHomeController = new CompanyHomeController(companyDao);

            pageTitle = "Add something";
        };

    // Act
    Because of = () => result = companyHomeController.Add();

    // Assert
    private It should_display_a_view = () => result.ShouldBeAView();

}

When I run the test, it fails and I get this message:

System.NullReferenceException: Object reference not set to an instance of an object.
at ..Commons.Hosts.Web.Mvc.Base.BaseController.SetPageTitle(String title) in C:\Projects\Commons\.Commons.Hosts\Web\Mvc\Base\BaseController.cs:line 87
at ..Hosts.Web.Areas.Company.Controllers.CompanyHomeController.Add() in C:\Projects\\Hosts\.Hosts.Web\Areas\Company\Controllers\CompanyHomeController.cs:line 93
at ..Hosts.Web.Specs.Areas.Company.Controllers.when_the_company_add_page_is_requested.<.ctor>b__1() in C:\Projects\Hosts\.Hosts.Web.Specs\Areas\Company\Controllers\CompanyHomeControllerSpecs.cs:line 43
at Machine.Specifications.Utility.RandomExtensionMethods.InvokeAll(IEnumerable`1 actions) in d:\BuildAgent-02\work\9f23de4d4da9eb12\Source\Machine.Specifications\Utility\RandomExtensionMethods.cs:line 32
at Machine.Specifications.Model.Context.EstablishContext() in d:\BuildAgent-02\work\9f23de4d4da9eb12\Source\Machine.Specifications\Model\Context.cs:line 86

I feel it's something blooming obvious, but I can't quite see it. As the CompanyHomeController is the SUT, I don't quite see why I'd have to touch upon the BaseController. Should I be stubbing the latter out? If so, why?


Solution

  • The SetPageTitle is probably trying to access the HttpContext which is not available in the unit test and which you might need to mock. Unfortunately as you haven't shown this method it is difficult to provide more help.