2

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?

Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108

2 Answers2

3

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

    //...
}
JamesR
  • 745
  • 4
  • 15
1

I finally found a solution, based on https://stackoverflow.com/a/29939664/902792

public class SearchResponseBuilder
{
    public static SearchResponse Build(string errorMessage)
    {
        var ctors = typeof (SearchResponse).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
        var neededCtor = ctors.First(
            ctor =>
                ctor.GetParameters().Count() == 5);
        SearchResponse response = neededCtor.Invoke(new object[]
        {
            "distinguishedName",
            null, // System.DirectoryServices.Protocols.DirectoryControl[]
            null, // System.DirectoryServices.Protocols.ResultCode
            errorMessage,
            null // System.Uri[]
        }) as SearchResponse;
        return response;
    }
}
Community
  • 1
  • 1
Stefan
  • 71
  • 1
  • 6