假货单元测试对我来说很新鲜。我以前从未这样做过,所以我决定练习它,但有一个问题是我无法调试假货单元测试,因为 Shims.Context.Create() 抛出空异常。当我运行测试时,它可以工作,但是当我调试它时,我得到了抛出空异常。如何解决?
类:文件阅读器
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);
}
}
}