类:FileReader
namespace FakingExample
{
public class FileReader
{
private readonly string _path;
public FileReader(string path)
{
_path = path;
}
public string Read()
{
using (var fs = new FileStream(_path, FileMode.Open))
{
var sr = new StreamReader(fs);
return sr.ReadToEnd();
}
}
}
}
伪造FileReader类的单元测试:
using System;
using FakingExample;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
namespace FakingFileReader.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
{
// Arrange
const string path = "irrelevant";
const string expected = "contents";
var target = new FileReader(path);
// shim the FileStream constructor
System.IO.Fakes.ShimFileStream.ConstructorStringFileMode =
(@this, p, f) =>
{
var shim = new System.IO.Fakes.ShimFileStream(@this);
};
// shim the StreamReader constructor
System.IO.Fakes.ShimStreamReader.ConstructorStream =
(@this, s) =>
{
var shim = new System.IO.Fakes.ShimStreamReader(@this)
{
// shim the ReadToEnd method
ReadToEnd = () => expected
};
};
// Act
var actual = target.Read();
// Assert
Assert.AreEqual(expected, actual);
}
}
}