MS伪造使用私有构造函数返回类的静态方法 [英] MS Fakes Static Method that Returns Class with Private Constructor

查看:117
本文介绍了MS伪造使用私有构造函数返回类的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试伪造/存根

System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name

我想知道如何分配GetComputerDomain以返回名称为"TestDomain"的域.我可以返回一个空域,如下所示:

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; };

但是我认为主要问题是Domain类没有公共构造函数,因此我无法执行以下操作:

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"
        };
    };

如何解决此问题?我认为仅与Moq一起使用是不可能的,因为我与MS Fakes一起使用了Moq.是否可以使用一个,另一个或两者来完成此任务?如果不是,我还有其他选择吗?

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.

推荐答案

如果您只想使用Fakes,这对我有用

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);
        }
    }

需要注意的两件事

  • 从静态Get...Domain方法返回匀场对象
  • 要查找Name属性,必须使用ActiveDirectoryPartition类,因为DomainActiveDirectoryPartition的子类,并且是在其中定义的地方.
  • Return a shimmed object from the static Get...Domain methods
  • To find the Name property, had to use ActiveDirectoryPartition class since Domain is a subclass of ActiveDirectoryPartition and that is where it is defined.

这篇关于MS伪造使用私有构造函数返回类的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆