这是我的界面
public interface IWork
{
string GetIdentifierForItem(Information information);
}
和我的班级
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) 创建信息模拟
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 快速入门指南中的一些链接。我知道我错过了一些东西。您能通过指导如何进行单元测试来帮助我吗?