How to use Moq to satisfy a MEF import dependency for unit testing?

前端 未结 2 446
耶瑟儿~
耶瑟儿~ 2021-01-13 15:49

This is my interface

public interface IWork
{
    string GetIdentifierForItem(Information information);
}

and my class

publ         


        
相关标签:
2条回答
  • 2021-01-13 15:52

    You don't need to Mock the Lazy<T,TMetadta>. It is flexible enough to work with your test. Instead, Mock the IWindowTypeInfo

    [TestMethod]
    public void GetIDTest()
    {
        var windowTypeInfoMock = new Mock<IWindowTypeInfo>();
        windowTypeInfoMock.Setup(foo => foo.Name).Returns("Data");
        windowTypeInfoMock.Setup(foo => foo.UniqueID).Returns("someString");
        var lazyWindow =
             new Lazy<IWindowType, IWindowTypeInfo>(windowTypeInfoMock.Object);
    
        var WindowTypesList = new List<Lazy<IWindowType, IWindowTypeInfo>>();
        WindowTypesList.Add(lazyWindow);
    
        var a = new A();
        a.WindowTypes = WindowTypesList;
        var InfoMock = new Mock<Information>();
        InfoMock.Setup(foo => foo.TargetName).Returns("Data");
    
        string expected = "someString";
        string actual;
        actual = a.GetIdentifierForItem(InfoMock.Object);
        Assert.AreEqual(expected, actual);
    }
    

    Your test passes on my machine with only small modifications, you do not need to use a composition container for this test.

    0 讨论(0)
  • 2021-01-13 16:15

    This is how it may be done, after setting up the mocks

    1) Creating a CompositionContainer, that holds the imports.

    2) Adding Mocks to the container.

    container.ComposeExportedValue(mock.Object);
    

    3) Create an instance of tested class

    4) Compose mocks to the import

    container.ComposeParts(instance);
    
    0 讨论(0)
提交回复
热议问题