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:
Changing the visibility of Tenant
doesn't "feel" right. What are my alternatives to unit test my derived controllers?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With