在.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表示嵌入式资源文件的相对路径。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值