Search code examples
c#.netunit-testingmoqmef

C# - Assign Mocked dependencies that are Imported from MEF


I'm using MEF for dependency injection and I'm at this point writing a unit test in which I'd have to inject a mocked dependency, but I have declared it as { get; protected set; } which renders me unable to do it.

The dependency is imported using the [Import] attribute, which means it isn't passed via constructor or anything similar.

What is the right approach, and by "right" I mean it doesn't violate any principle like SOLID and similar, to solve this inconvenient?

Code:

[Import]  // MEF is able to inject it even tho it's set accessor is protected
IMyDependencie MyDependency { get; protected set; }

Solution

  • Unless the class is sealed, you can create a class which inherits from it and sets the protected property:

    public class TestClass : ClassToBeTested
    {
        public TestClass(IMyDependencie mockDependency)
        {
            // Set protected property:
            MyDependency = mockDependency;
        }
    }
    

    Then in the setup of your unit test, create the object with a mocked dependency:

     // These will be fields in the test class.
     Mock<IMyDependencie> mockDependency = new Mock<IMyDependencie>();
    
     TestClass tc = new TestClass(mockDependency.Object);
    

    An alternative - which you would have to use if the class under test is sealed - is to use a PrivateObject to set the property, or just just plain old reflection to do it.