Landeeyo Landeeyo - 1 month ago 4
C# Question

How to create an instance of SearchResponse class (which has no public constructors)?

I want to mock a method which returns SearchResponse object from namespace System.DirectoryServices.Protocols. I use Moq. I need to create its instance. It doesn't have any constructors.

Normally in my project it's result of casting DirectoryResponse object to SearchResponse class, where DirectoryReponse is a result of SendRequest method of LdapConnection object.

Is there any way to create instance of SearchReponse class?

Answer

You can do it With Typemock Isolator by faking SearchResponse with Members.CallOriginal flag to assure that the original implementation is called.

*Make sure that you set the state state your fake before using it.

Another way is to use FakeDependencies. Isolator Automatically creates fakes for the ctors parameters, passes them and returns an instance of your class(SearchResponse). You can create and pass some of the dependencies or all to FakeDependencies methods and it will delegate them to the constractor upon creation.

Examples:

class MyClass
{
    public SearchResponse GetSearchResponse()
    {
        return null;
    }
}

Real:

[TestMethod]
public void CreateSearchResponse_RealObjectWithFakedDependencies()
{
    var myClass = new MyClass();
    SearchResponse searchResponse = Isolate.Fake.Dependencies<SearchResponse>();
    Isolate.WhenCalled(() => myClass.GetSearchResponse()).WillReturn(searchResponse);

    SearchResponse sr = myClass.GetSearchResponse(); // returns SearchResponse

    //...
}

Fake:

[TestMethod]
public void CreateSearchResponse_FakeObject_StateShouldBeSet_OriginalBehavior()
{
    var myClass = new MyClass();
    SearchResponse fakeSearchResponse = Isolate.Fake.Instance<SearchResponse>(Members.CallOriginal, ConstructorWillBe.Called);
    Isolate.WhenCalled(() => myClass.GetSearchResponse()).WillReturn(fakeSearchResponse);

    SearchResponse sr = myClass.GetSearchResponse(); // returns fakeSearchResponse

    //...
}
Comments