Moq C # built in class

I am trying to make fun of the SearchResultCollection class. However, when I try to catch the GetSourceLoaded call, my test throws an exception:

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

My code is:

 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 such a class? The property in question has only 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; } 
+6
source share
2 answers

I'm afraid you can’t.

As you said, the property is not virtual. Another option would be to fool the interface, but I checked, and there isn’t for this class (according to the MSDN document).

There are other isolation frameworks that can do this. Microsoft Moles can do this, just like TypeMock.


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

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

+8
source

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

+2
source

Source: https://habr.com/ru/post/900149/


All Articles