Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq C# built in class

Tags:

c#

moq

I'm trying to mock out the SearchResultCollection class. However, when I try to intercept a call to the PropertiesLoaded getter, my test throws an Exception:

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

My Code:

Mock<SearchResultCollection> searchResultMock = new Mock<SearchResultCollection>();

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

Has anyone successfully mocked out a class like this? The property in question only has a getter and is not virtual.

    //
    // 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; }
like image 462
MarkP Avatar asked Oct 26 '11 17:10

MarkP


2 Answers

I'm afraid you can't.

Like you said the property isn't virtual. Another option would have been to mock the interface but I checked and there isn't one for this class (according to the MSDN doc).

There are some other isolation framework which can do this though. Microsoft Moles is able to do it, so is TypeMock.


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

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

like image 79
Gilles Avatar answered Sep 27 '22 22:09

Gilles


This is not possible with Moq. You can only mock interfaces, abstract classes, and classes with virtual methods (and in the latter case, you can only use Setup() to mock the behavior of virtual methods).

like image 34
Dave C Avatar answered Sep 27 '22 23:09

Dave C