简体   繁体   中英

How to unit test a method with dynamic return values?

I have a method like this:

public List<string> GetAllDomains()
{
       List<string> domains = new List<string>();

      DirectoryContext directoryContext = new DirectoryContext(DirectoryContextType.Domain);

      using (Domain currentDomain = Domain.GetDomain(directoryContext))
      using (Forest forest = currentDomain.Forest)
      {
          DomainCollection addDomainsInForest = forest.Domains;
          foreach (Domain domain in addDomainsInForest)
          {
              domains.Add(domain.Name);
          }
      }

      return domains; 

}

How can I write an unit test for this method? Thanks.

Since your method speaks with Active Directory, then you cannot create a unit test for it. You can create an integration test. Integration tests are tests that test how your code integrates with the environment (or with some other code). In your case, you want to test how your code integrates with Active Directory.

In this case, the integration test can only work in a specific environment which you know the names of domains that it will contain.

Having said that, if your code contains a good amount of logic, you can create an abstraction by hiding active directory code behind some interface/interfaces and then you can unit test that logic by mocking these interfaces.

In your case however, I cannot see that your method contains much logic. Its a simple consumption of the Active Directory API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM