首页 > 解决方案 > How to user Assert for methods with return type void in MSTest

问题描述

I have a method in my c# application similar to below.

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

Now, I'm trying to write a unit testcase for the above method using MStest. I have written something as below.

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

Now how do I know if the testcase failed or succeeded. How do I use Assert here?
Any help is highly appreciated.

标签: c#taskmstestvoid

解决方案


If you test the AnotherMethod directly, you will see if it's succefull. When it throws an Exception the test is failed. The SampleMethod does only implement the try catch and calls the AnotherMethod() which can be tested directly.

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

This test fail if it throws an Execption. When the method do not throw an Exception, it is successfull.


推荐阅读