是否可以将属性传递给ExpectedException中的消息?

时间:2016-05-12 19:34:33

标签: 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表达式或属性参数类型的数组创建表达式。”。

1 个答案:

答案 0 :(得分:2)

在你的情况下,我不会使用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
        }
    }