在.NET单元测试中使用嵌入式资源

目录

介绍

背景

使用代码


介绍

有时,单元测试的逻辑要求使用嵌入到库中的资源。最有可能的是,该文件保留了黑盒的初始数据,并已通过单元测试进行了测试。这篇文章将展示如何使用这类资源。

背景

假设我们需要编写单元测试,以验证黑盒是否为空文件引发异常。在Visual Studio中创建测试项目后,我们立即将空的test.dat文件添加到Resources文件夹中。

该资源的Build Action属性必须设置为Embedded Resource,这意味着该文件已嵌入可执行文件中。

使用代码

我们可以将资源读取为流,而只有一个方法扩展GetEmbeddedResourceStream将参数传递为资源Resources.test.dat的路径。单元测试期望BlackBox类在读取获取的资源时在Operation方法中引发异常。

namespace EmbeddedResource_demo
{
    public class BlackBox
    {
        public void Operation(Stream stream)
        {
            if (stream.Length == 0)
                throw new ArgumentException("Stream is empty");
            // Do some logic
        }
    }

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        [ExpectedException(typeof(ArgumentException), "Stream is empty")]
        public void TestFileIsEmpty()
        {
            using (var inputStream = 
              Assembly.GetExecutingAssembly().GetEmbeddedResourceStream("Resources.test.dat"))
            {
                var blackbox = new BlackBox();
                blackbox.Operation(inputStream);
            }
        }
    }
}

添加类AssemblyExtensions以定义新方法,该方法返回嵌入式资源文件的数据流。

public static Stream GetEmbeddedResourceStream
       (this Assembly assembly, string relativeResourcePath)
        {
            if (string.IsNullOrEmpty(relativeResourcePath))
                throw new ArgumentNullException("relativeResourcePath");

            var resourcePath = String.Format("{0}.{1}",
                Regex.Replace(assembly.ManifestModule.Name, @"\.(exe|dll)$", 
                      string.Empty, RegexOptions.IgnoreCase), relativeResourcePath);

            var stream = assembly.GetManifestResourceStream(resourcePath);
            if (stream == null)
                throw new ArgumentException(String.Format("The specified embedded resource 
                                            \"{0}\" is not found.", relativeResourcePath));
            return stream;
        }

参数assembly表示包含资源的程序集。参数relativeResourcePath表示嵌入式资源文件的相对路径。

发布了69 篇原创文章 · 获赞 133 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/mzl87/article/details/104116538