0

是否可以使用 rhino 模拟示例模拟文件调用:

  private ServerConnection LoadConnectionDetailsFromDisk(string flowProcess)
  {
       var appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
       var bodyFile = Path.Combine(appPath, @"XML\ServerConnections.xml");

        if (File.Exists(bodyFile))
        {
            //more logic
  }

因此,我试图模拟 File.Exists 方法,使其返回 true,因此无论文件是否存在,我都能够测试逻辑的下一个分支。这可能吗?

4

2 回答 2

1

这是您的原始片段:

private ServerConnection LoadConnectionDetailsFromDisk(string flowProcess)
{
   var appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
   var bodyFile = Path.Combine(appPath, @"XML\ServerConnections.xml");

    if (File.Exists(bodyFile))
    {
        //more logic
    }
}

cadrell 基本上没有使用 System.IO 库(无法模拟),而是说要添加一个抽象层,您可以对其进行模拟:

private ServerConnection LoadConnectionDetailsFromDisk(string flowProcess)
{
   var appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
   var bodyFile = Path.Combine(appPath, @"XML\ServerConnections.xml");

    if (FileExists(bodyFile))
    {
        //more logic
    }
}

public bool FileExists(bodyFile) { return File.Exists(bodyFile) }

现在,在您的测试中,您可以定义一个使用大部分现有代码的 PartialMock(允许您对其进行测试),但允许您仅覆盖 FileExists 方法:

var myPartialMock = mockRepo.PartialMock(typeof(MyObject));

myPartialMock.Expect(m=>m.FileExists("")).IgnoreArguments().Return(true);

myPartialMock.LoadConnectionDetailsFromDisk("myProcess");

现在,从 if 语句内部调用总是返回 true。

其他需要考虑的事情;我看到一个基于文件存在的 if 块。您没有指定代码,但我敢打赌,除了您(因为您可以更改代码)之外的任何人,该代码都会打开或操作我们现在知道存在的文件。因此,整个方法与您可以和不能进行单元测试的边界擦肩而过。您可以考虑重构此方法以从另一个函数获取 Stream(允许您模拟该函数并使用测试数据注入 MemoryStream),但在某些时候您将刮擦“沙箱”的边缘,只需要相信 .NET 团队完成了他们的工作,并且对 File.Exists、File.Open 等的调用按预期工作。

于 2012-06-21T14:24:23.447 回答
0

使用接口将其抽象出来。

public Interface IFileChecker
    {
       bool FileExists(string path)
    }

然后使用该接口创建您的模拟对象。

IFileChecker fileChecker = mocks.Stub<IFileChecker>();

using (mocks.Record())
            {
                fileChecker.Stub(i => i.FileExists(Arg<string>.Is.Any)).Return(true);
            }
于 2012-06-21T15:01:39.937 回答