这是我的界面
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/