Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this ASP.NET MVC controller more testable?

I have a controller that overrides OnActionExecuting and does something like this:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    string tenantDomain = filterContext.RouteData.Values["tenantDomain"] as string;
    if (!string.IsNullOrWhiteSpace(tenantDomain))
    {
        using (var tx = BeginTransaction())
        {
            this.Tenant = repo.FindOne(t => t.Domain == tenantDomain);
        }
    }
}

Tenant is a protected property with a private setter. The class itself is an abstract base controller that my real controllers derive from. I have code in other controllers that looks a lot like this:

if (Tenant == null)
{
   // Do something
}
else
{
   // Do something else
}

How do I test this code? What I need to do is to somehow set the Tenant property, but I can't because:

  1. It's a protected property, and
  2. It has a private setter

Changing the visibility of Tenant doesn't "feel" right. What are my alternatives to unit test my derived controllers?

like image 425
Ragesh Avatar asked Nov 14 '22 10:11

Ragesh


1 Answers

Here's how I would do it:

Create a concrete class in your test project, that inherits from your abstract controller, and exposes Tenant as a public property. There is nothing wrong with having mock or dummy code in the test project (and of course, dummy code that just facilitates testing, should never be in the production projects).

If that is not a good fit for your situation; you could use Visual Studio's Private Accessor Assembly feature to generate a type where you can access your Tenant property. It is available in the IDE, or in command-line form.

like image 105
driis Avatar answered Jan 17 '23 17:01

driis