本文介绍了如何模拟System.DirectoryServices.SearchResult?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果你有一个方法,它需要进行测试的需要SearchResult所组成的列表
If you have a method that needs to be tested that takes a list of SearchResults
public virtual void ProcessResults(IList<SearchResult> list)
{
//Code to tests here
}
你怎么小样信息搜索结果的该列表?
How do you mock up that list of SearchResult?
注:允许不低级别的注入框架(例如TypeMock)
Note: No low-level injection frameworks (eg TypeMock) allowed.
推荐答案
目前我有这个丑陋的code
Currently i have this ugly code
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);
innerList.Add(value);
var lowerKey = propertyInfo.Name.ToLower(CultureInfo.InvariantCulture);
dictionary.Add(lowerKey, propertyCollection);
}
return searchResult;
}
private static ArrayList GetInnerList(object resultPropertyCollection)
{
var propertyInfo = typeof(ResultPropertyValueCollection).GetProperty("InnerList", nonPublicInstance);
return (ArrayList) propertyInfo.GetValue(resultPropertyCollection, null);
}
private static void SetPropertiesFieled(SearchResult searchResult)
{
var propertiesFiled = typeof(SearchResult).GetField("properties", nonPublicInstance);
propertiesFiled.SetValue(searchResult, GetUninitializedObject<ResultPropertyCollection>());
}
private static T GetUninitializedObject<T>()
{
return (T) FormatterServices.GetUninitializedObject(typeof(T));
}
}
它用于...
which is used...
var searchResult = SearchResultFactory.Construct(new
{
name = "test1",
givenName = "John",
sn = "Smith"
});
这篇关于如何模拟System.DirectoryServices.SearchResult?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!