我正在尝试模拟SearchResultCollection类。但是,当我尝试拦截对PropertiesLoaded getter的调用时,我的测试将引发异常:

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: x => x.PropertiesLoaded

我的代码:
Mock<SearchResultCollection> searchResultMock = new Mock<SearchResultCollection>();

// Set up collection that will be returned
string[] tempData = { "one", "two" };
searchResultMock.SetupGet(x => x.PropertiesLoaded).Returns(tempData);

有人成功 mock 过这样的类(class)吗?有问题的属性只有一个 setter/getter ,并且不是虚拟的。
    //
    // Summary:
    //     Gets the System.DirectoryServices.DirectorySearcher properties that were
    //     specified before the search was executed.
    //
    // Returns:
    //     An array of type System.String that contains the properties that were specified
    //     in the System.DirectoryServices.DirectorySearcher.PropertiesToLoad property
    //     collection before the search was executed.
    public string[] PropertiesLoaded { get; }

最佳答案

恐怕你做不到。

就像您说的那样,该属性不是虚拟的。另一种选择是模拟接口(interface),但我检查了该类,但没有一个(根据MSDN文档)。

但是,还有一些其他隔离框架可以做到这一点。
Microsoft Moles能够做到这一点,TypeMock也是如此。

Microsoft Moles:http://research.microsoft.com/en-us/projects/moles/

TypeMock:http://www.typemock.com/

10-04 11:33