Search code examples
c#unit-testingmicrosoft-fakes

Unit Testing Interface and abstract memebers using shims in Visual Studio 2013


I have below code which I want to unit test.

public abstract class Manager : MyPermissions, IManager
{   
    public IManager empManager { get; set; }

    public void UpdatePermission()
    {
       if (empManager != null)
           empManager.UpdatePermissions();
    }
}

I don't have an class that derives from the above class within the same library otherwise I would have preferred to test the derived class for testing the above code. For now I have below test which I am running but it actually doesn't hit the actual code for testing.

[TestMethod]
public void empManagerGetSet()
{
    using (ShimsContext.Create())
    {
        StubIManager sManager;
        sManager = new StubIManager();
        sManager.empManagerGet = () => { return (IManager)null; };
        var result = sManager.empManagerGet;
        Assert.IsNotNull(result);
    }
}

Is there any other approach I can use to write a better UT in this scenario?


Solution

  • You don't say what your MyPermissions class looks like, if it has a constructor and if so what it does.. so this might not be the right approach. Note, you'd also need to implement stubs for any abstract methods defined in the Manager class.

    If you just want to test the empManager property, you can just create a testable derived type in your test project and test the properties on that. This would give you something like this:

    class TestableManager : Manager {
    }
    

    Then have a test something like this:

    [TestMethod]
    public void TestManagerPropertyRoundTrip {
        var sut = new TestableManager();
        Assert.IsNull(sut.empManager);
        sut.empManager = sut;
        Assert.AreEqual(sut, sut.empManager);
    }
    

    You can also test any other methods on the Manager class, via the TestableManager, since it only exists to make the class concrete.

    There's a suggestion in the comments on your question that there is no point testing public properties. This is somewhat opinion based. I tend to take the view that if you were following a test first based approach, you wouldn't necessarily know that the properties were going to be implemented using auto properties, rather than a backing field. So, the behaviour of being able to set a property and retrieve it again is something that I would usually test.