如何模拟System.DirectoryServices.SearchResult?

Sim*_*mon 5 .net c# unit-testing mocking active-directory

如果您有一个需要测试的方法,它会获取SearchResults列表

public virtual void ProcessResults(IList<SearchResult> list)
{
    //Code to tests here
}
Run Code Online (Sandbox Code Playgroud)

你如何模拟SearchResult列表?

注意:不允许使用低级注入框架(例如TypeMock).

Sim*_*mon 11

目前我有这个丑陋的代码

public static class SearchResultFactory
{
    const BindingFlags nonPublicInstance = BindingFlags.NonPublic | BindingFlags.Instance;
    const BindingFlags publicInstance = BindingFlags.Public | BindingFlags.Instance;

    public static SearchResult Construct<T>(T anonInstance)
    {
        var searchResult = GetUninitializedObject<SearchResult>();
        SetPropertiesFieled(searchResult);
        var dictionary = (IDictionary)searchResult.Properties;
        var type = typeof(T);
        var propertyInfos = type.GetProperties(publicInstance);
        foreach (var propertyInfo in propertyInfos)
        {
            var value = propertyInfo.GetValue(anonInstance,null);
            var propertyCollection = GetUninitializedObject<ResultPropertyValueCollection>();
            var innerList = GetInnerList(propertyCollection);
            if (propertyInfo.PropertyType.IsArray)
            {
                var stringArray = (String[])value;
                foreach (var subValue in stringArray)
                {
                    innerList.Add(subValue);
                }
            }
            else
            {
                innerList.Add(value);
            }
            var lowerKey = propertyInfo.Name.ToLower(CultureInfo.InvariantCulture);
            dictionary.Add(lowerKey, propertyCollection);
        }
        return searchResult;
    }

    static ArrayList GetInnerList(object resultPropertyCollection)
    {
        var propertyInfo = typeof(ResultPropertyValueCollection).GetProperty("InnerList", nonPublicInstance);
        return (ArrayList) propertyInfo.GetValue(resultPropertyCollection, null);
    }

    static void SetPropertiesFieled(SearchResult searchResult)
    {
        var propertiesFiled = typeof(SearchResult).GetField("properties", nonPublicInstance);
        propertiesFiled.SetValue(searchResult, GetUninitializedObject<ResultPropertyCollection>());
    }

    static T GetUninitializedObject<T>()
    {
        return (T) FormatterServices.GetUninitializedObject(typeof(T));
    }
}
Run Code Online (Sandbox Code Playgroud)

使用...

var searchResult = SearchResultFactory.Construct(
         new
         {
             name = "test1",
             givenName = "John",
             sn = "Smith",
             rights = new String[] { "READ", "WRITE" }
         });
Run Code Online (Sandbox Code Playgroud)