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

前端 未结 2 445
耶瑟儿~
耶瑟儿~ 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. It is flexible enough to work with your test. Instead, Mock the IWindowTypeInfo

    [TestMethod]
    public void GetIDTest()
    {
        var windowTypeInfoMock = new Mock();
        windowTypeInfoMock.Setup(foo => foo.Name).Returns("Data");
        windowTypeInfoMock.Setup(foo => foo.UniqueID).Returns("someString");
        var lazyWindow =
             new Lazy(windowTypeInfoMock.Object);
    
        var WindowTypesList = new List>();
        WindowTypesList.Add(lazyWindow);
    
        var a = new A();
        a.WindowTypes = WindowTypesList;
        var InfoMock = new Mock();
        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.

提交回复
热议问题