这是我的接口如何使用起订量来满足一个单元测试MEF进口的依赖?
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)创建一个模拟慵懒而设置,它需要在道具返回值erty得到
var windowMock = new Mock<Lazy<IWindowType, IWindowTypeInfo>>(); windowMock.Setup(foo => foo.Metadata.Name).Returns("Data"); windowMock.Setup(foo => foo.Metadata.UniqueID).Returns("someString");
(2)创建的窗口类型列表和上述嘲笑对象,然后将其设置为所创建的一个目的
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”和veiwing细节,它看起来像我做的东西,我不应该做的事情。
但我不知道怎么做的其他方式。我已阅读Moq快速入门指南中的一些链接。我知道我错过了一些东西。你能通过指导如何进行单元测试来帮助我吗?