模拟DirectoryEntry的Children属性和DirectoryEntries的Find方法

时间:2016-02-26 13:30:23

标签: .net unit-testing

模拟System.DirectoryServices.DirectoryEntry的Children属性和DirectoryEntries的Find方法有什么好方法?我试图使用适配器模式来包装DirectoryEntry和DirectoryEntries,但我不确定如何实现Children属性:

public interface IDirectoryEntries
{
    IDirectoryEntry Find(string name);
}

public interface IDirectoryEntry
{
    .. 
    IDirectoryEntries Children { get; }
    ..
}

子元素属性如果在框架中定义如下:

class DirectoryEntry
{
    ..
    public DirectoryEntries Children { get; }
    ..
}

此致 弗兰克

1 个答案:

答案 0 :(得分:0)

谢!

首先,对于单元测试,要做的就是创建为您的测试需求指定的DirectoryEntries集合,这自然会导致如何实现模拟。我创建了一个模拟Children属性并通过Typemock Isolator实现Find方法的简单示例:

public class TestEntries
{
    public static LinkedList<DirectoryEntry> entries = new LinkedList<DirectoryEntry>();
}

[TestClass]
public class UnitTest1
{
    [TestInitialize]
    public void SetUp()
    {
        for (int i = 0; i < 5; i++)
        {
            var fakeEntry = Isolate.Fake.Instance<DirectoryEntry>();
            Isolate.WhenCalled(() => fakeEntry.Name).WillReturn("name" + i);
            TestEntries.entries.AddFirst(fakeEntry);
        }
    }

    [TestMethod, Isolated]
    public void TestMethod1()
    {
        var fake1 = Isolate.Fake.Instance<DirectoryEntry>();
        Isolate.WhenCalled(() => fake1.Children).WillReturnCollectionValuesOf(TestEntries.entries);

        var fakeDE = Isolate.Fake.Instance<DirectoryEntries>();
        Isolate.WhenCalled(() => fakeDE.Find("")).DoInstead(context =>
        {
            string name = context.Parameters[0] as string;
            foreach (DirectoryEntry entry in TestEntries.entries)
            {
                if (entry.Name.Equals(name))
                    return entry;
            }
            return null;
        });

        Assert.AreEqual("name4", fakeDE.Find("name4").Name);
    }
}

希望它可以帮到你!