【问题标题】:Is possible to property to a message in ExpectedException?是否可以在 ExpectedException 中对消息进行属性处理?
【发布时间】:2016-05-12 19:34:32
【问题描述】:

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

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表达式或数组创建表达式。”。

【问题讨论】:

  • 您拥有的代码正在验证 Exception 是否正确抛出异常。我希望您想要测试 /your/ 代码,而不是 Microsoft 的。在这种情况下,文件名将像往常一样从您的类/方法中抛出。
  • 有一个控制台应用程序读取数据库,获取文件名和 URL 服务,然后创建一个实例并调用将文件名作为对象属性传递的方法。我需要抛出异常的原因是控制台应用程序处理该异常以记录和发送电子邮件。但是我正在创建的这个测试方法只是测试一个文件的验证,所以,我认为目前所有的过程都不会发生。

标签: c# unit-testing expected-exception


【解决方案1】:

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

【讨论】:

  • 事实上,我必须确保这个TestMethod抛出异常,然后我从Scott Chamberlain更改源,插入ExpectedException并将!=信号更改为==,以验证异常返回的类型和消息。非常感谢斯科特。
  • 我修复了它,现在它会检查是否总是抛出异常。您只需在 try 块的末尾添加一个Assert.Fail(
  • 我是 StackOverflow 的新手。试着把代码放在这里,但我认为这是不允许的。而不是 throw new Exception(String.Format("Error on file {0}", FileName));我有一种方法来验证文件名 ValidateFileName(IncorrectFileName);在这种方法中,我必须抛出一个异常情况,文件名无效。添加 Assert.Fail 确实可以纠正它。再次感谢斯科特。
  • 编辑您的问题并将代码作为更新放在那里。
  • 另一个小改动。如果第一次抛出忽略了第二次验证,我将验证类型异常和消息放在一个中。代码更改 if(e.GetType() != typeof(Exception) && e.Message != String.Format("Error on file {0}", FileName)) throw;
猜你喜欢
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 2014-08-24
  • 2011-06-10
  • 1970-01-01
  • 2017-03-16
  • 2018-09-30
  • 1970-01-01
相关资源
最近更新 更多