如何在 MSTest 中为 return 类型为 void 的方法使用断言

How to user Assert for methods with return type void in MSTest

我的 C# 应用程序中有一个类似于下面的方法。

public async Task SampleMethod()
{
    try
    {
        //some code 
        await AnotherMethod();
        // some code
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message.ToString());        
    }
}

现在,我正在尝试使用 MStest 为上述方法编写单元测试用例。我写了如下内容。

[TestMethod]
public async Task SampleMethodTest()
{
    ClassName cn = new ClassName();
    await cn.SampleMethod();
 }

现在我怎么知道测试用例是失败还是成功。我如何在这里使用 Assert?
非常感谢任何帮助。

如果你直接测试AnotherMethod,你会看到它是否成功。当它抛出异常时,测试失败。 SampleMethod只实现了try catch,调用了AnotherMethod()可以直接测试

[TestMethod]
public async Task SampleMethodTest()
{
   ClassName cn = new ClassName();
   await cn.AnotherMethod();
 }

如果抛出异常,此测试将失败。当该方法没有抛出异常时,它是成功的。

如果您的方法更改了对象的状态,您可以验证对象的状态是否与预期的一样。如果没有,您可以使用 Mock(带有 Moq 之类的框架)来验证与其他对象的协作。请注意,您可能需要将 AnotherMethod 提取到另一个 class,以便您可以模拟和验证调用。

另请注意,您应该尝试设计您的软件,以便您可以在大多数单元测试中使用输出验证和状态验证。使用 mock 进行通信验证可能会导致难以维护的误报和单元测试。

根据我在其他回答中的评论,我尝试向您展示如何获取控制台输出。您可以从控制台读取所有文本,您必须将 StringWriter() 设置到控制台:

[TestMethod]
public async Task SampleMethodTest()
{
    using (StringWriter stringWriter = new StringWriter())
    {
        Console.SetOut(stringWriter);

        ClassName cn = new ClassName();
        await cn.SampleMethod();

        string consoleOutput = stringWriter.ToString();

        Assert.IsFalse(consoleOutput.Contains("Exception"));
    }
}

我希望这能奏效。我还没有用 UnitTest 尝试过,只用了一个控制台程序。