c# - 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.
解决方案
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.
推荐阅读
- sql-server - IF NOT EXIST 插入 ELSE IF 更新 ELSE IF EXISTS 并且不是数字 DELETE From WHERE
- python-3.x - AttributeError:只能使用 .dt 访问器和 0yrs 0mon 格式的 datetimelike 值
- c - 如何在 PM 服务器 Minix 中发送消息
- .net - 如何使用 Excel 互操作将 XLS 文件转换为 CSV 并将其返回而不是保存
- wordpress - WordPress 更改管理页面上的 URL
- python-3.x - Python 控制台和 Python 虚拟机是如何工作的?
- javascript - 我怎样才能让我的动画也朝着另一个方向工作?
- primefaces - 如何在 Primefaces 上向 chartJS 添加数据标签
- javascript - 获取“未捕获的参考错误:$ 未定义” - 脚本以正确的顺序加载 - 并从控制台工作
- c++ - 不明白为什么我需要在最后几行返回