使用FileStream模拟使用

时间:2012-06-21 15:16:58

标签: c# rhino-mocks

我一直在尝试使用文件流来模拟使用但是无法完成此操作并且不确定如何执行此操作,我正在使用rhino mock。

private Connection LoadConnectionDetailsFromDisk(string bodyFile)
{     
   //logic before
   using (FileStream fs = File.Open(bodyFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
   {
     return this.serverConfiguration.LoadConfiguration(fs, flowProcess);
   }
    //more logic
}

有人能告诉我如何模拟使用(FileStream ....)所以我能够访问代码的这个分支吗?

5 个答案:

答案 0 :(得分:9)

你必须通过接口方法抽象File.Open()然后你就可以模拟对它的调用。

所以

1)创建一个界面:

public interface IFileDataSource
{
   FileStream Open(string path,
                   FileMode mode,
                   FileAccess access,
                   FileShare share);
}

2)更改LoadConnectionDetailsFromDisk()如下:

private Connection LoadConnectionDetailsFromDisk(string path, IFileDataSource fileSource)
{     
   using (FileStream fs = fileSource.Open(bodyFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
   {
      return this.serverConfiguration.LoadConfiguration(fs, flowProcess);
   }

   //more logic
}

3)在测试中模拟界面并注入模拟

// create a mock instance
var sourceMock = MockRepository.GenerateMock<IFileDataSource>();

// setup expectation
sourceMock.Expect(m => m.Open("path", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
         .CallBack(
 delegate (string path, FileMode mode, FileAccess access, FileShare share)
 {
      // handle a call

     return true;
 }).Repeat.Any();

// TODO: depends on how you are triggering LoadConnectionDetailsFromDisk method call
// inject a mock

考虑到LoadConnectionDetailsFromDisk()你不能将mock直接注入此方法调用froma test,所以请说明如何调用此方法。

答案 1 :(得分:1)

您可以使用SystemWrapper lib来实现此目的。它包含包装系统类的接口和类,使您能够使用此类对单元测试方法进行单元化。

答案 2 :(得分:1)

System.IO.Exception projectNuGet package也允许模拟FileStreams

要使用该功能,首先必须稍微更改FileStream的获取方式,例如:

private readonly IFileSystem _fileSystem; // this is from System.IO.Exception

// This is assuming dependency injection to insert the mock file system during testing, 
// or the real one in production
public YourConstructor(IFileSystem fileSystem)
{
   _fileSystem = fileSystem;
}

private Connection LoadConnectionDetailsFromDisk(string bodyFile)
{     
   using (Stream fs = _fileSystem.FileStream.Create(bodyFile, FileMode.Open))
   {
       return this.serverConfiguration.LoadConfiguration(fs, flowProcess);
   }

   //more logic
}

答案 3 :(得分:0)

我会重构该方法,以便将FileStream传递给方法,以便您可以创建文件流的模拟

private Connection LoadConnectionDetailsFromDisk(FileStream bodyFile)
{ 
  ....
}

如果你真的想要获得幻想,你可以随时接受一个I​​Stream,然后模拟那个IStream,但是Rhino支持创建混合类的模拟

 MockRepository mocks = new MockRepository();
 FileStream basket = mocks.CreateMock<FileStream>();

答案 4 :(得分:0)

我通过创建FileStream子类来处理它。基本构造函数确实要求我们打开一个实际文件,因此我包括一个简单的文本文件,该文件设置为“ Content”和“ Include if newer”,我们将其打开为只读且可共享。

然后覆盖我实际需要的方法。就我而言,我需要write方法,并且我需要对所写的内容做一些事情,所以我注入了一个回调来调用。

private class CustomFileStream : FileStream
{
    private Action<string> WriteAction { get; }
    public CustomFileStream(Action<string> writeAction)
        // FileStream is notoriously hard to mock, so we inherit from it and we are a lightweight, real (but unused) FileStream underneath
        : base(Path.Combine(new ExecutionDirectory().Path /* Handle the execution directory in your own way */, "Content/DummyTextFile.txt"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    {
        this.WriteAction = writeAction;
    }

    public override bool CanWrite => true;
    public override void Write(ReadOnlySpan<byte> buffer)
    {
        this.WriteAction(Encoding.UTF8.GetString(buffer));
    }
}