为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 try catch 块中编写 C# 单元测试以获得正确的代码覆盖率

如何在 try catch 块中编写 C# 单元测试以获得正确的代码覆盖率

C#
繁星淼淼 2021-06-04 07:29:53
我有以下代码:public class MyControllerClass : ApiController  {     private readonly IManager _manager;   public MyControllerClass(IManager manager)   {     this._manager = manager;   }   pubic async Task<IHttpActionResult> GetRequest()     {       try         {           await this._manager.GetRequest();           return this.ok();         }       catch (Exception ex)        {           this.logger.Error("Error message", ex);           throw this.HTTPResponseException("Request failed message", ex);         }      }} public class ManagerFake : IManagerFake  {      public Task GetRequest()      {          return Task.FromResult(true);      }  }     我正在使用 NUnit 进行单元测试。对于单元测试,我在 IOC 容器中注册了一个 FakeManager 类,该类包含 GetResult() 方法,并在执行时简单地返回 Task.FromResult(true)。这允许执行 try 块中的逻辑,从而满足该部分的适当代码覆盖率。我遇到的问题是如何使用相同的 FakeManager 类创建一个测试,该类将抛出异常,以便在无法对 GetRequest 进行两次唯一调用时执行 catch 块逻辑并满足代码覆盖率() 方法,因为它不接受可用于区分两个不同调用的输入参数?
查看完整描述

2 回答

?
动漫人物

TA贡献1815条经验 获得超10个赞

使用返回 true 的相同 ManagerFake 类。制作一个不同的 IManager 实现来引发错误。

或者,使用模拟对象库来创建模拟对象实例,该实例与您在每个测试中想要的行为完全一致。


查看完整回答
反对 回复 2021-06-05
  • 2 回答
  • 0 关注
  • 142 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信