您必须通过接口方法进行抽象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()
您不能从测试中直接将模拟注入此方法调用,因此请说明如何调用此方法。