Search code examples
unit-testingvisual-studio-2008protected

How to test a protected method?


I have an ASP.NET page that is the base to many more derived pages and it contains the following protected method

protected Change SetupApproval(string changeDescription)
{
    Change change = Change.GetInstance();
    change.Description = changeDescription;
    change.DateOfChange = DateTime.Now;
    change.MadeBy = Common.ActiveDirectory.GetUsersFullName(AccessCheck.CurrentUser());
    change.Page = PageName;
    return change;
}

I want to write the following Unit test

[TestMethod]
public void SetupApproval_SubmitChange_ValidateDescription()
{
    var page = new DerivedFromBaseClass();
    var messageToTest = "This is a test description";

    var change = (page as InternalAppsPage).SetupApproval(messageToTest);

    Assert.IsTrue(messageToTest == change.Description);
}

I'm sure there's a lot wrong with this code (so feel free to suggest corrections), but my main goal is to start implementing some tests for this entire project. I decided to start small - one method at a time. I first tried creating a new Test Project, but then I can't access the SetupApproval method because it is protected. My next attempt was to put the TestMethod inside of the base page, but then there's no way to Run Tests.

Lastly, I'm using Visual Studio 2008's default test framework.


Solution

  • Two options:

    • Assuming DerivedFromBaseClass is a class which solely exists for testing, just give it a new public (or internal) method which just calls SetupApproval and returns the return value.
    • Make the method protected internal instead, and make sure you have InternalsVisibleTo set up for your test assembly so it has access to internal methods. Document that this is for the sake of testing.

    The first option is cleaner, the second is simpler, particularly if you have a lot of protected methods and the base class is non-abstract.