2

I am using Ldapconnection.Sendrequest because I am running on Linux, so I can only use classes from the System.DirectoryServices.Protocols namespace.

The code works perfectly well against a live Active Directory, but here is an example anyway.

// retrieves the distinguishedname for all groups, starting from dc=test,dc=local
var request = new SearchRequest("dc=test,dc=local", "(Objectclass=group)", "distinguishedname");
var searchResponse = ldapConnection.SendRequest(request) as SearchResponse;

My question is, how can this be unit tested? I would like to unit test it because a different searchResponse will cause a different path to be taken through code.

I have tried mocking SearchResponse: (How to create an instance of SearchResponse class (which has no public constructors)?)

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;

But I cannot find a way to mock SearchResponse.Entries, as SearchResultEntryCollection and SearchResultEntry are (seemingly) unmockable. It's as though the dotnet team has gone out of its way to make this area completely unmockable.

I'm new to using LdapConnection (previously I could use the AccountManagement class, as I was running in Windows), so maybe I shouldn't be using LdapConnection in the first place?

Equally, I'd be open to running the AD tests in memory, as I would for database access, but I cannot find a way to do so.

Many thanks for you help, Dan

danwag
  • 355
  • 2
  • 14
  • Did you try with Moq framework or any such, to mock your dependencies for desired testing? – Ak777 Jan 12 '22 at 05:02
  • Thanks @Ak777, I did try using Moq, but I haven't been able to mock SearchResponse.Entries, because it appears to be impossible to mock SearchResultEntryCollection and SearchResultEntry. – danwag Jan 12 '22 at 11:04
  • It would be more helpful to check on this further if you share the full more code or via any git, removing sensitive or non-shareable lines/information. – Ak777 Jan 12 '22 at 16:04
  • To be honest, there's nothing to share. The code works when talking to an AD controller, but, as I couldn't actually create a mock, there's no unit test to share ¯\\_(ツ)_/¯ – danwag Jan 13 '22 at 10:05

0 Answers0