我一直试图模拟使用文件流,但无法完成这个,我不知道该怎么做,我正在使用犀牛模拟.
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
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我如何模拟使用(FileStream ....)所以我能够访问代码的这个分支?
sll*_*sll 10
你必须File.Open()通过接口方法进行抽象,然后你就可以模拟对它的调用.
所以
1)创建一个界面:
public interface IFileDataSource
{
FileStream Open(string path,
FileMode mode,
FileAccess access,
FileShare share);
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
考虑到LoadConnectionDetailsFromDisk()你不能直接将mock注入这个方法调用froma test,所以请说明如何调用这个方法.