c# - 是否可以将属性赋予 ExpectedException 中的消息?

标签 c# unit-testing expected-exception

我正在尝试验证返回的异常和消息,但此消息中的文件名是可变的。是否可以仅使用一种方法使用单元测试来做到这一点?

public static string FileName
        {
            get
            {
                return "EXT_RF_ITAUVEST_201605091121212";
            }
        }

        [TestMethod()]
        [ExpectedException(typeof(Exception), String.Format("Error on file {0}", FileName))]
        public void ValidarNomeArquivo_DataNomeIncorreta_Mensagem()
        {
            throw new Exception(String.Format("Error on file {0}", FileName));
        }

上面的代码返回错误“属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式。”。

最佳答案

在您的情况下,我不会使用ExpectedException,而只是手动执行它所执行的逻辑。

    public static string FileName
    {
        get
        {
            return "EXT_RF_ITAUVEST_201605091121212";
        }
    }

    [TestMethod()]
    public void ValidarNomeArquivo_DataNomeIncorreta_Mensagem()
    {
        //This try block must contain the entire function's logic, 
        // nothing can go after it to get the same behavor as ExpectedException.
        try
        {
            throw new Exception(String.Format("Error on file {0}", FileName));

            //This line must be the last line of the try block.
            Assert.Fail("No exception thrown");
        }
        catch(Exception e)
        {
            //This is the "AllowDerivedTypes=false" check. If you had done AllowDerivedTypes=true you can delete this check.
            if(e.GetType() != typeof(Exception))
                throw;

            if(e.Message != String.Format("Error on file {0}", FileName))
                throw;

            //Do nothing here
        }
    }

关于c# - 是否可以将属性赋予 ExpectedException 中的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37195952/

相关文章:

c# - 是否可以像加载XML文件一样使用XDocument的功能加载DGML文件?

c# - 向网站添加静态子域的推荐方法是什么?

c# - 使用 Linq to SQL SELECT @@DBTS

node.js - Protractor E2E - 您如何管理数据库?

AngularJS Jasmine 单元测试 - Controller 方法从未被调用

python - 使用 pytest 和假设进行异常处理和测试

java - 如何使用 ExpectedException 规则在一个测试中测试多个异常?

C# ASP.NET : how to access cache when no HttpContext. 当前是否可用(为空)?

unit-testing - 如何使用结构/接口(interface)来模拟依赖项以进行测试

C 宏未按预期工作