运行伪造单元测试时抛出null异常

时间:2013-09-12 12:06:11

标签: c# unit-testing microsoft-fakes

假货单元测试对我来说很新鲜。我从来没有这样做过,所以我决定练习它,但有一个问题,我无法调试假单位测试,因为Shims.Context.Create()抛出null异常。当我运行测试时,它工作但是当我调试它时,我得到了抛出null异常。如何解决?

类: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);
        }
    }
}

0 个答案:

没有答案
相关问题