【问题标题】:How to check error message in C#? [closed]如何在 C# 中检查错误消息? [关闭]
【发布时间】:2017-10-07 07:54:32
【问题描述】:

这是一种检查负值后显示的错误消息的方法吗?我可以检查是否抛出了正确的异常,但是如果我的方法不会抛出带有负数的异常,只需将 WriteLine 写入错误输出流。

public List<int> MyMethod()
{
    ...
    try
    {
        //add elements to list
    }
    catch(Exception e)
    {
        Error.WriteLine("Element cannot be negative, but other elements are ok");
    }
    ...
}

[TestMethod]
public void TestWithNegatives()
{
    try
    {
        List<int> list = MyMethod();
        //there is a negative int in list, so there'll be an error message
    }
    catch (Exception e)
    {
        //Can I check here the error message, if there isn't exception thrown in mymethod?
    }
}

【问题讨论】:

  • 你试过单元测试吗?
  • “显示”是什么意思。你有一个 GUI,一个控制台应用程序?
  • 将一堆行写入控制台以在各种情况下显示是或者可以是一种简单但实用的方法。同样,您可以在调试时设置断点并检查元素,这可能会为您节省大量用于控制台的 if 语句。
  • @programmo 你当然可以,但如果没有看到代码,很难说如何。您可以通过添加方法和单元测试的代码示例来改进您的问题
  • @BojanB 当然,我添加了我的代码

标签: c# testing assertion


【解决方案1】:

由于您已经处理了异常并且它没有被重新抛出,因此您无法在测试中再次处理它。

但是由于您知道有一条消息写入Console.Error,您可以通过将Console.Error 重定向到自定义StringWriter 来检查这一点,然后检查写入的内容:

public void TestWithNegatives()
{
    using (StringWriter sw = new StringWriter())
    {
        Console.SetError(sw);
        List<int> list = MyMethod();
        // Check output in "Error":
        Assert.IsFalse(string.IsNullOrEmpty(sw.ToString())); 
    }
}

【讨论】:

  • 非常感谢!这是我需要的。
猜你喜欢
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多