1

偽物の単体テストは私にとって非常に新しいものです。今までやったことがなかったので実践してみることにしましたが、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 クラスの Fakes 単体テスト:

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);
        }
    }
}
4

0 に答える 0