Mock System.Net.FtpClient GetHash方法

时间:2015-12-31 15:04:58

标签: c# .net unit-testing mocking moq

是否可以模拟public FtpHash GetHash(string path)

类的System.Net.FtpClient.IFtpClient

问题是FtpHash有一个内部构造函数。有没有办法嘲笑它?

修改

作为模拟的一部分,我想测试所有方法代码行

    public bool Verify(string localFile, string removeFile)
    {
        bool res = false;
        using (IFtpClient client = new FtpClient())
        {
            var hash = client.GetHash(removeFile);
            if (hash != null)
            {
                if (hash.Verify(localFile))
                {
                    this.logger.Info("file pass Verify test");
                    res = true;
                }
                else
                {
                    this.logger.Error("file fail Verify test");
                }
            }
        }
        return res;
    }

因此hash.Verify应该能够返回true / false。

1 个答案:

答案 0 :(得分:3)

是的,您可以模拟界面IFtpClient和方法FtpHash GetHash(string path),但您必须使用反射:

var ctor = typeof(FtpHash)
                 .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];
var ftphash = (FtpHash) ctor.Invoke(new object[]{ });

var fakeFtpClient = new Mock<IFtpClient>();
fakeFtpClient.Setup( x => x.GetHash(It.IsAny<string>()).Return(ftpHash);

修改

根据您提供的代码,您根本无法使用moq。 您必须进行一些重构才能使用它...(代码与FtpClient耦合)

hash.Verify异常的原因很简单:

状态m_algorithmFtpHash的私人成员)是FtpHashAlgorithm.NONE ...(here is the source code

此成员的setter是内部的,因此您必须再次使用reflaction,然后使用deployitemattributte将散列文件部署到localFile的位置。

IMO在这种情况下你根本不应该使用moq(UT不会小,可读,可维护和快速,除非你打包这些类......)。我建议您使用代码编织工具,如MsFakes / TypemMock ISolator。然后任何事情都会简单得多..(当我在.Net世界时,我使用了MsFakes以及犀牛模拟/ moq ......)。

以下图表可能会帮助您解决方案策略:

enter image description here

BTW代码看起来像代码永远不会发生任何变化的情况之一......我根本就不知道它......它只是觉得我浪费时间......