如何在 C# 中检查错误消息?

How to check error message in C#?

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

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?
    }
}

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

但是由于您知道消息已写入 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())); 
    }
}