I'm trying to fake/stub out
System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name
I'd like to know how to assign GetComputerDomain to return a Domain with a Name of "TestDomain". I can return a null domain as follows:
System.DirectoryServices.ActiveDirectory.Fakes.ShimDomain
.GetComputerDomain = () => { return null; };
But I think the main issue is that the Domain class does not have a public constructor so I can't do the following:
System.DirectoryServices.ActiveDirectory.Fakes.ShimDomain
.GetComputerDomain = () =>
{
return new System.DirectoryServices.ActiveDirectory.Domain()
{
Name = "TestDomain"
};
};
How do I get around this issue? I don't think it's possible with Moq alone which I am using along side of MS Fakes. Is it possible to use one, the other, or both to accomplish this? If not what are my other alternatives?
Side note: I'm not really looking for alternatives to getting domain name. I'd really like to how to use this with my current implementation as I want a better understanding of how to mock and fake things out that may fall under this category in the future. Alternatives are welcome but really looking forward to answer to existing question.
If you just want to use Fakes, this worked for me
[TestMethod]
public void TestDomain()
{
using (ShimsContext.Create())
{
System.DirectoryServices.ActiveDirectory.Fakes.ShimDomain.GetComputerDomain = () =>
{
return new System.DirectoryServices.ActiveDirectory.Fakes.ShimDomain();
};
System.DirectoryServices.ActiveDirectory.Fakes.ShimActiveDirectoryPartition.AllInstances.NameGet =
partition =>
{
return "My Name";
};
string curName = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
Assert.AreEqual("My Name", curName);
}
}
Two things to note
Get...Domain
methodsActiveDirectoryPartition
class since Domain
is a subclass of ActiveDirectoryPartition
and that is where it is defined.