开发者

Should I unit test a class for having MEF attributes?

I want to refactor a DLL to make it MEFable too开发者_运维技巧. Should I unit test whether a class is decorated with [Export] or [Import] and other MEF attributes?


Your tests should focus more on the goal instead of the mechanism. Create tests that verify things like "if I throw types X, Y and Z together in a container, then I can pull an IFoo interface from the container", like this:

[Test]
public void Can_get_IFoo_from_container_with_Foo_Bar_Baz()
{
    var catalog = new TypeCatalog(typeof(Foo), typeof(Bar), typeof(Baz));
    using (var container = new CompositionContainer(catalog))
    {
        var test = container.GetExportedValue<IFoo>();
    }
}

This is no longer a real "unit" test because it involves multiple classes and an IoC container. We just call them "composition tests".


After thinking some hours and reading some TDD blogs again I should say, YES, I have to test whether my class has MEF attributes or not.

So before refactoring my classes I write unit tests in that way:

[TestClass]
public class When_SampleClass_mefable
{
   [TestMethod]
   [TestCategory("LFF.Kabu.Win.Login.ViewModel.SampleClass")]
   public void Should_SampleClass_be_marked_with_Export_Attibute()
   {
       //arrange
       var info = (typeof (SampleClass));

       //act
       var attr = info.GetCustomAttributes(true);

       var hasExportAttribute = 
           attr.Where(x => x.GetType() == typeof (ExportAttribute))
               .Where(x => ((ExportAttribute)x).ContractType == typeof(SampleClass))
               .Count() > 0;
       //assert
       Assert.IsTrue(hasExportAttribute, "SampleClass is not marked with Export.");
    }
}

For other MEF attributes like [ImportingConstructor] or [PartCreationPolicy] I do it the same way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜