c# - 如何使用 Moq 来满足单元测试的 MEF 导入依赖?

标签 c# .net unit-testing moq mef

这是我的界面

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

和我的类(class)

public class A : IWork
{
[ImportMany]
public IEnumerable<Lazy<IWindowType, IWindowTypeInfo>> WindowTypes { get; set; }

public string GetIdentifierForItem(Information information)
{
    string identifier = null;
    string name = information.TargetName;

    // Iterating through the Windowtypes 
    // searching the 'Name' and then return its ID  
    foreach (var windowType in WindowTypes)
    {
        if (name == windowType.Metadata.Name)
        {
            identifier = windowType.Metadata.UniqueID;
            break;
        }
    }
    return identifier;
}
}

问题:我想对方法进行单元测试GetIdentifierForItem

这是我尝试解决它的方法 -

(1)创建一个模拟 Lazy 并设置它需要在属性获取时返回的值

var windowMock = new Mock<Lazy<IWindowType, IWindowTypeInfo>>(); windowMock.Setup(foo => foo.Metadata.Name).Returns("Data"); windowMock.Setup(foo => foo.Metadata.UniqueID).Returns("someString");

(2)创建窗口类型列表和上面的mocked对象,然后将其设置为创建的A对象

var WindowTypesList = new List<IWindowType, IWindowTypeInfo>>();
WindowTypesList.Add(windowMock.Object);
A a = new A();
a.WindowTypes = WindowTypesList;

(3) 创建信息mock

var InfoMock = new Mock<Information>();
InfoMock.Setup(foo => foo.TargetName).Returns("Data");

将以上所有内容放在一起作为单元测试

[TestMethod]
public void GetIDTest()
{
    var windowMock = new Mock<Lazy<IWindowType, IWindowTypeInfo>>();
    windowMock.Setup(foo => foo.Metadata.Name).Returns("Data");
    windowMock.Setup(foo => foo.Metadata.UniqueID).Returns("someString");

    var WindowTypesList = new List<Lazy<IWindowType, IWindowTypeInfo>>();
    WindowTypesList.Add(windowMock.Object);

    A a = new A();
    a.WindowTypes = WindowTypesList;
    var InfoMock = new Mock<Information>();
    InfoMock.Setup(foo => foo.TargetName).Returns("Data");

    string expected = "someString"; // TODO: Initialize to an appropriate value
    string actual;
    actual = a.GetIdentifierForItem(InfoMock.Object);
    Assert.AreEqual(expected, actual);

}

此单元测试无法执行并抛出异常“TargetInvocationException”并查看详细信息,看起来我正在做一些我不应该做的事情。

但我不确定其他方法如何。我已经阅读了 Moq 快速入门指南中的一些链接。我知道我错过了什么。你能指导我如何对此进行单元测试吗?

最佳答案

在设置模拟之后,这是可以完成的

1) 创建一个包含导入的 CompositionContainer。

2) 将模拟添加到容器中。

container.ComposeExportedValue(mock.Object);

3) 创建被测类实例

4) 为导入编写模拟

container.ComposeParts(instance);

关于c# - 如何使用 Moq 来满足单元测试的 MEF 导入依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222654/

相关文章:

.net - 如何在c/c++/vb.net/c#中获取CPU温度?

c# - 使用 MSTest 仅运行所有测试集的一部分

c++ - 测试自定义标准兼容容器

asp.net-mvc - 如何使用 Moq 模拟 session 对象集合

c# - 如何从 Visual Studio 将 View 导航到其 Controller ?

c# - 为什么 IDictionary<TKey,TValue> 不/不能实现 ILookup<TKey,TValue>?

c# - Ping.SendAsync() 从 0.0.0.0 返回重播,如何获取 ping 地址?

c# - 为什么我的对象不需要 ServiceKnownType?

javascript - 从 EXTJS ComboBox 的 JSON 存储中检索 url 参数

c# - Entity Framework 迁移 - 参照完整性约束违规