当前位置:   article > 正文

XUnit单元测试(实用项目)——看完不会用你打我

xunit

一、简介

xUnit.net 是针对 .NET 的免费、开源单元测试框架,可并行测试、数据驱动测试。测试项目需要同时引用 xUnit和被测试项目,从而对其进行测试。测试编写完成后,用 Test Runner 来测试项目,Test Runner 可以读取测试代码,并且知道所会使用的测试框架,然后执行,并显示结果。

二、支持平台

xUnit.net 目前支持 .Net Framework、.Net Core、.Net Standard、UWP、Xamarin ,可以在这些平台使用 xUnit 进行测试。

三、核心思想

单元测试的核心思想:万物皆虚拟(mock data)、测试某个类时要假定其他类都正常、单元测试代码和被测试代码的目录结构最好一致。
配置项是虚拟的,配置项各属性的值要重新设置。
类实例是虚拟的,类实例中的不同方法返回什么结果要提前设置。
Http请求是虚拟的,不同http请求返回什么结果要提前设置。

四、XUnit具体用法详解

欲写单元测试首先得有要测试的功能/服务,写服务的过程就不在这里赘述了,写单元测试的时候我会把对应的服务关键代码截图过来让大家对照着看,下面正式开始:

1、准备环境

1.1新建项目

1.2安装依赖项及项目结构概览(FluentAssertions、Moq)

2、对AnalyzerService.cs进行单元测试

先来个简单点的对AnalyzerService.cs进行单元测试,具体可参照下述步骤:

  • 创建对应的测试类AnalyzerServiceUnitTest.cs
  • 声明测试对象IAnalyzerService _sut(System Under Test待测系统的缩写)
  • 在构造方法中创建AnalyzerService实例并赋值给测试对象,创建实例所需的参数都要用mock数据,缺哪些就声明哪些
  • 声明并用new对mock数据初始化后还要对其中的属性/方法进行设置才能使用(呼应第三点核心思想,这也是单元测试最重要的一步)
  • 测试对象创建完毕后,要根据IAnalyzerService创建测试方法(单元测试要包含其中的所有方法,甚至更多)
  • 单一方法业务较复杂时可以根据if条件将其拆分成多个测试方法,所以测试方法可能多于接口原有的方法
  • 若原方法有返回值可以根据返回值是否符合预期来进行断言,若原方法没返回值只要不报错即可,若需要判断异常我这也有处理方法
  • 下面直接上代码,我会尽可能的添加注释帮助大家理解

  1. namespace LearnUnitTest.Test.Services
  2. {
  3. public class AnalyzerServiceUnitTest
  4. {
  5. private readonly string _token;
  6. private readonly string _fileMetadataId;
  7. //声明测试对象
  8. private readonly IAnalyzerService _sut;
  9. //声明new AnalyzerService()所需的参数
  10. private readonly Mock<ISauthService> _sauthService;
  11. private readonly Mock<IFileMetadataService> _fileMetadataService;
  12. private readonly Mock<IProcessTimeService> _processTimeService;
  13. private readonly Mock<IErrorRecordService> _errorRecordService;
  14. private readonly Mock<IOptions<TimeSettings>> _timeSettings;
  15. private readonly Mock<IOptions<ReferencingServices>> _referencingServices;
  16. private readonly Mock<IOptions<ErrorRecordSetting>> _errorRecordSetting;
  17. private readonly Mock<IActivityService> _activityService;
  18. private readonly Mock<ILogger<AnalyzerService>> _logger;
  19. private const string ExceptionMsg = "UT_Exception_Message";
  20. public AnalyzerServiceUnitTest()
  21. {
  22. _token = Guid.NewGuid().ToString();
  23. _fileMetadataId = "UT_FileMetadataId";
  24. _sauthService = new Mock<ISauthService>();
  25. _fileMetadataService = new Mock<IFileMetadataService>();
  26. _processTimeService = new Mock<IProcessTimeService>();
  27. _errorRecordService = new Mock<IErrorRecordService>();
  28. _timeSettings = new Mock<IOptions<TimeSettings>>();
  29. _referencingServices = new Mock<IOptions<ReferencingServices>>();
  30. _errorRecordSetting = new Mock<IOptions<ErrorRecordSetting>>();
  31. _activityService = new Mock<IActivityService>();
  32. _logger = new Mock<ILogger<AnalyzerService>>();
  33. //mock数据创建实例后还要根据需求对其中的属性/方法进行设置才能使用
  34. InitOptions();
  35. InitServices();
  36. //创建AnalyzerService实例并赋值给测试对象
  37. _sut = new AnalyzerService(_sauthService.Object, _fileMetadataService.Object,
  38. _processTimeService.Object, _errorRecordService.Object,
  39. _timeSettings.Object, _referencingServices.Object, _errorRecordSetting.Object,
  40. _activityService.Object, _logger.Object);
  41. }
  42. [Fact]
  43. public async Task Analyze_ShouldSuccess_WhenHasLatestProcessTime()
  44. {
  45. LatestProcessTimeRecord latestProcessTimeRecord = new LatestProcessTimeRecord()
  46. {
  47. //设置返回值非空
  48. LatestProcessTime = DateTime.UtcNow
  49. };
  50. //AnalyzerService中GetLatestProcessTimeAsync()返回空和非空会进行不同的逻辑处理,所以将其拆分成两个方法
  51. //通过重写GetLatestProcessTimeAsync()的返回值对不同的情况进行逻辑覆盖
  52. _processTimeService.Setup(x=>x.GetLatestProcessTimeAsync(It.IsAny<string>()))
  53. .ReturnsAsync(latestProcessTimeRecord);
  54. var exception = await Record.ExceptionAsync(async () => await _sut.AnalyzeAsync());
  55. exception.Should().BeNull();
  56. }
  57. [Fact]
  58. public async Task Analyze_ShouldSuccess_WhenNoLatestProcessTime()
  59. {
  60. LatestProcessTimeRecord latestProcessTimeRecord = new LatestProcessTimeRecord()
  61. {
  62. //设置返回值为空
  63. LatestProcessTime = null
  64. };
  65. //AnalyzerService中GetLatestProcessTimeAsync()返回空和非空会进行不同的逻辑处理,所以将其拆分成两个方法
  66. //通过重写GetLatestProcessTimeAsync()的返回值对不同的情况进行逻辑覆盖
  67. _processTimeService.Setup(x => x.GetLatestProcessTimeAsync(It.IsAny<string>()))
  68. .ReturnsAsync(latestProcessTimeRecord);
  69. Exception exception = await Record.ExceptionAsync(async () => await _sut.AnalyzeAsync());
  70. exception.Should().BeNull();
  71. }
  72. [Fact]
  73. public async Task Analyze_ShouldRecordErrorLog_WhenThrowException()
  74. {
  75. LatestProcessTimeRecord latestProcessTimeRecord = new LatestProcessTimeRecord()
  76. {
  77. LatestProcessTime = DateTime.UtcNow
  78. };
  79. _processTimeService.Setup(x => x.GetLatestProcessTimeAsync(It.IsAny<string>()))
  80. .ReturnsAsync(latestProcessTimeRecord);
  81. _fileMetadataService.Setup(x => x.QueryMetadatasAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
  82. .Callback(() =>
  83. {
  84. throw new Exception(ExceptionMsg);
  85. });
  86. await Record.ExceptionAsync(async () => await _sut.AnalyzeAsync());
  87. //LogLevel参数写法1
  88. _logger.Verify(x => x.Log(
  89. It.Is<LogLevel>(logLevel => logLevel == LogLevel.Error),
  90. It.IsAny<EventId>(),
  91. It.IsAny<It.IsAnyType>(),
  92. It.IsAny<Exception>(),
  93. It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
  94. Times.Once);
  95. //LogLevel参数写法2
  96. _logger.Verify(x => x.Log(
  97. LogLevel.Error,
  98. It.IsAny<EventId>(),
  99. It.IsAny<It.IsAnyType>(),
  100. It.IsAny<Exception>(),
  101. It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
  102. Times.Once);
  103. }
  104. [Fact]
  105. public async Task NoImplement_ShouldThrowException_Method01()
  106. {
  107. Func<Task> result = async () => await _sut.NoImplementAsync(_token);
  108. //链式进行异常判断写法1
  109. await result.Should().ThrowAsync<NotImplementedException>();
  110. }
  111. [Fact]
  112. public async Task NoImplement_ShouldThrowException_Method02()
  113. {
  114. Exception exception = await Record.ExceptionAsync(async () => await _sut.NoImplementAsync(_token));
  115. //链式进行异常判断写法2
  116. exception.Should().BeOfType<NotImplementedException>();
  117. }
  118. [Fact]
  119. public async Task NoImplement_ShouldThrowException_Method03()
  120. {
  121. try
  122. {
  123. //try...catch进行异常判断
  124. await _sut.NoImplementAsync(_token);
  125. Assert.True(false);
  126. }
  127. catch (NotImplementedException ex)
  128. {
  129. Assert.True(true);
  130. }
  131. catch
  132. {
  133. Assert.True(false);
  134. }
  135. }
  136. [Theory]
  137. [InlineData(NamingFileType.MaxwellSMLSummary, "EVQ", "maxwellsmlsummary-evq")]
  138. [InlineData(NamingFileType.MaxwellSMLSummary, "evq", "maxwellsmlsummary-evq")]
  139. [InlineData(NamingFileType.MaxwellSMLSummary, "EVT", "maxwellsmlsummary-evt")]
  140. [InlineData(NamingFileType.MaxwellSMLSummary, "evt", "maxwellsmlsummary-evt")]
  141. [InlineData(NamingFileType.MaxwellSMLSummary, "PROD", "maxwellsmlsummary")]
  142. [InlineData(NamingFileType.MaxwellSMLSummary, "prod", "maxwellsmlsummary")]
  143. [InlineData(NamingFileType.MaxwellSMLSummary, "", "maxwellsmlsummary")]
  144. [InlineData(NamingFileType.General, "evQ", "general-evq")]
  145. [InlineData(NamingFileType.General, "EvT", "general-evt")]
  146. [InlineData(NamingFileType.General, "PRod", "general")]
  147. [InlineData(NamingFileType.General, "", "general")]
  148. public void GetContainerName_ShouldReturnCorrectContainer(NamingFileType fileType, string envionment, string expect)
  149. {
  150. string containerName = fileType.GetContainerName(envionment);
  151. containerName.Should().BeEquivalentTo(expect);
  152. }
  153. private void InitOptions()
  154. {
  155. TimeSettings timeSettings = new TimeSettings()
  156. {
  157. DefaultUploadTime = "2022-06-01T00:00:00.000Z"
  158. };
  159. //IOptions<T>类型的变量通过Value属性来获取实际的参数值,所以这里要重写Value属性
  160. _timeSettings.Setup(x => x.Value).Returns(timeSettings);
  161. ReferencingServices referencingServices = new ReferencingServices()
  162. {
  163. DataPartitionId = "DataPartition-Id",
  164. FileServiceURL = "https://global.FileService.URL",
  165. ActivityServiceURL = "https://global.ActivityService.URL",
  166. ProcessStatusServiceURL = "https://global.ProcessStatusService.URL"
  167. };
  168. _referencingServices.Setup(x => x.Value).Returns(referencingServices);
  169. ErrorRecordSetting errorRecordSetting = new ErrorRecordSetting()
  170. {
  171. DefaultMaxRetryCount = 5
  172. };
  173. _errorRecordSetting.Setup(x => x.Value).Returns(errorRecordSetting);
  174. }
  175. private void InitServices()
  176. {
  177. //AnalyzerService中调用了ISauthService.GetToken(),不重写GetToken()则所有用到此方法的地方返回值都是null(返回值是string类型)
  178. _sauthService.Setup(x => x.GetToken()).ReturnsAsync(_token);
  179. List<FileMetadataGetResponse> fileMetadatas = new List<FileMetadataGetResponse>()
  180. {
  181. new FileMetadataGetResponse() { Id = _fileMetadataId }
  182. };
  183. //当需要重写的方法有参数时,根据参数类型用It.IsAny<T>()代替即可
  184. _fileMetadataService.Setup(x => x.QueryMetadatasAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
  185. .ReturnsAsync(fileMetadatas);
  186. WellTestingEmission wellTestingEmission = new WellTestingEmission()
  187. {
  188. Id = _fileMetadataId,
  189. CreatedTime = DateTime.UtcNow,
  190. Emissions = new List<EmissionInfo>()
  191. {
  192. new EmissionInfo()
  193. {
  194. Name = "CO2EstimatedEmissionForGas",
  195. Unit = "T",
  196. Value = 0.0f
  197. }
  198. }
  199. };
  200. _fileMetadataService.Setup(x => x.GetFileContentByMetadataIdAsync(It.IsAny<string>(), It.IsAny<string>()))
  201. .ReturnsAsync(wellTestingEmission);
  202. _errorRecordService.Setup(x => x.InsertProcessErrorAsync(It.IsAny<ErrorBaseRecord>(), It.IsAny<string>(), It.IsAny<string>()));
  203. _errorRecordService.Setup(x => x.UpdateProcessErrorAsync(It.IsAny<ErrorBaseRecord>(), It.IsAny<string>(), It.IsAny<string>()));
  204. _activityService.Setup(x => x.InsertOrUpdateActivityAsync(It.IsAny<string>(), It.IsAny<WellTestingEmission>(), It.IsAny<OperationalActivity>(), It.IsAny<string>()));
  205. }
  206. }
  207. }

3、对ActivityService.cs进行单元测试

本节在AnalyzerServiceUnitTest.cs单元测试的基础上添加了对http请求的处理(直接用System.Net.Http.HttpClient发送Post/Get请求),单元测试不能发送真实的http请求,所以我们要对不同的http请求分别设置对应的返回值(mock数据),具体可参照下述步骤:

  • 创建对应的测试类ActivityServiceUnitTest.cs
  • 声明测试对象IActivityService _sut(System Under Test待测系统的缩写)
  • 在构造方法中创建ActivityService实例并赋值给测试对象,创建实例所需的参数都要用mock数据,缺哪些就声明哪些
  • 声明并用new对mock数据初始化后还要对其中的属性/方法进行设置才能使用(呼应第三点核心思想,这也是单元测试最重要的一步)
  • 测试对象创建完毕后,要根据IActivityService创建测试方法(单元测试要包含其中的所有方法,甚至更多)
  • 单一方法业务较复杂时可以根据if条件将其拆分成多个测试方法,所以测试方法可能多于接口原有的方法
  • 若原方法有返回值可以根据返回值是否符合预期来进行断言,若原方法没返回值只要不报错即可,若需要判断异常我这也有处理方法(参考上一节
  • 下面直接上代码,我会尽可能的添加注释帮助大家理解

  1. namespace LearnUnitTest.Test.Services
  2. {
  3. public class ActivityServiceUnitTest
  4. {
  5. private readonly string _token;
  6. private readonly string _fileMetadataId;
  7. //多次用到的对象要定义成全局变量
  8. private readonly WellTestingEmission _wellTestingEmission;
  9. private readonly OperationalActivity _operationalActivity;
  10. //声明new ActivityService()所需的参数
  11. private readonly IActivityService _sut;
  12. private readonly Mock<ISauthService> _sauthService;
  13. private readonly Mock<IOptions<ReferencingServices>> _referencingServices;
  14. private readonly Mock<ILogger<ActivityService>> _logger;
  15. private readonly Mock<IHttpClientWrapperService> _httpClientWrapperSvc;
  16. public ActivityServiceUnitTest()
  17. {
  18. _token = Guid.NewGuid().ToString();
  19. _fileMetadataId = "UT_FileMetadataId";
  20. _sauthService = new Mock<ISauthService>();
  21. _referencingServices = new Mock<IOptions<ReferencingServices>>();
  22. _logger = new Mock<ILogger<ActivityService>>();
  23. _httpClientWrapperSvc = new Mock<IHttpClientWrapperService>();
  24. _wellTestingEmission = new WellTestingEmission()
  25. {
  26. JobId = "UT_JobId",
  27. JobName = "UT_JobName",
  28. CountryOfOrigin = "UT_CountryOfOrigin",
  29. CustomerName = "UT_CustomerName",
  30. FdpNumber = "UT_FdpNumber"
  31. };
  32. _operationalActivity = new OperationalActivity()
  33. {
  34. Wells = new[] { new Well() { Wellname = "UT_Wellname01", Wellfield = "UT_Wellfield01" } }
  35. };
  36. //mock数据创建实例后还要根据需求对其中的属性/方法进行设置才能使用
  37. InitOptions();
  38. InitServices();
  39. _sut = new ActivityService(_sauthService.Object, _httpClientWrapperSvc.Object,
  40. _referencingServices.Object, _logger.Object);
  41. }
  42. [Fact]
  43. public async Task ExtractActivity_ShouldSuccess()
  44. {
  45. var excepted = new ActivityCreateUpdateRequest
  46. {
  47. WellInfo = new WellData
  48. {
  49. WellName = _operationalActivity?.Wells[0]?.Wellname,
  50. FieldName = _operationalActivity?.Wells[0]?.Wellfield,
  51. CountryCode = _wellTestingEmission.CountryOfOrigin,
  52. ClientName = _wellTestingEmission.CustomerName
  53. },
  54. Execution = new ExecutionData
  55. {
  56. Id = _wellTestingEmission.JobId,
  57. Name = _wellTestingEmission.JobName,
  58. Time = Convert.ToDateTime(_wellTestingEmission.CreationDate),
  59. System = ExecutionSystem.Tallix,
  60. Status = ExecutionStatus.Completed
  61. },
  62. BusinessContext = new BusinessContextData
  63. {
  64. FDPNumber = _wellTestingEmission.FdpNumber
  65. },
  66. Details = new ActivityDetails
  67. {
  68. MetadataIds = new List<string>() { _fileMetadataId }
  69. }
  70. };
  71. RequestBase<ActivityCreateUpdateRequest> result = _sut.ExtractActivity(_fileMetadataId, _wellTestingEmission, _operationalActivity);
  72. //逐个属性对比属性值是否相同
  73. excepted.Should().BeEquivalentTo(result.Data);
  74. }
  75. [Fact]
  76. public async Task InsertOrUpdateActivity_ShouldSuccess_WhenInsert()
  77. {
  78. ResponseBase<ActivityBatchQueryResponse> activityBatchQueryResponse = new ResponseBase<ActivityBatchQueryResponse>()
  79. {
  80. Data = new ActivityBatchQueryResponse()
  81. {
  82. //TotalCount<=0
  83. TotalCount = 0
  84. }
  85. };
  86. ResponseBase<ActivityCreateResponse> activityCreateResponse = new ResponseBase<ActivityCreateResponse>()
  87. {
  88. Data = new ActivityCreateResponse() { Id= _wellTestingEmission.JobId }
  89. };
  90. //一个方法中调用多个PostAsync/GetAsync时,根据不同的参数类型来进行设置
  91. _httpClientWrapperSvc.Setup(x => x.PostAsync<RequestBase<ActivityBatchQueryRequest>, ResponseBase<ActivityBatchQueryResponse>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityBatchQueryRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  92. .Returns(Task.FromResult(activityBatchQueryResponse));
  93. _httpClientWrapperSvc.Setup(x => x.PostAsync<RequestBase<ActivityCreateUpdateRequest>, ResponseBase<ActivityCreateResponse>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityCreateUpdateRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  94. .Returns(Task.FromResult(activityCreateResponse));
  95. //方法没有返回值时,检查执行过程中不能有异常
  96. var exception = await Record.ExceptionAsync(async () => await _sut.InsertOrUpdateActivityAsync(_fileMetadataId, _wellTestingEmission, _operationalActivity, _token));
  97. exception.Should().BeNull();
  98. }
  99. [Fact]
  100. public async Task InsertOrUpdateActivity_ShouldSuccess_WhenInsert_Met401()
  101. {
  102. int calls = 0;
  103. ResponseBase<ActivityBatchQueryResponse> activityBatchQueryResponse = new ResponseBase<ActivityBatchQueryResponse>()
  104. {
  105. Data = new ActivityBatchQueryResponse()
  106. {
  107. //TotalCount<=0
  108. TotalCount = 0
  109. }
  110. };
  111. ResponseBase<ActivityCreateResponse> activityCreateResponse = new ResponseBase<ActivityCreateResponse>()
  112. {
  113. Data = new ActivityCreateResponse() { Id = _wellTestingEmission.JobId }
  114. };
  115. _httpClientWrapperSvc.Setup(x => x.PostAsync<RequestBase<ActivityBatchQueryRequest>, ResponseBase<ActivityBatchQueryResponse>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityBatchQueryRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  116. .Returns(Task.FromResult(activityBatchQueryResponse));
  117. //方法执行过程中主动抛出异常,且仅第一次执行时抛异常,之后就正常执行
  118. _httpClientWrapperSvc.Setup(x => x.PostAsync<RequestBase<ActivityCreateUpdateRequest>, ResponseBase<ActivityCreateResponse>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityCreateUpdateRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  119. .Returns(Task.FromResult(activityCreateResponse))
  120. .Callback(() =>
  121. {
  122. calls++;
  123. if (calls == 1)
  124. {
  125. throw new HttpRequestException("", new Exception(), HttpStatusCode.Unauthorized);
  126. }
  127. });
  128. var exception = await Record.ExceptionAsync(async () => await _sut.InsertOrUpdateActivityAsync(_fileMetadataId, _wellTestingEmission, _operationalActivity, _token));
  129. exception.Should().BeNull();
  130. }
  131. [Fact]
  132. public async Task InsertOrUpdateActivity_ShouldSuccess_WhenUpdate()
  133. {
  134. ResponseBase<ActivityBatchQueryResponse> activityBatchQueryResponse = new ResponseBase<ActivityBatchQueryResponse>()
  135. {
  136. Data = new ActivityBatchQueryResponse()
  137. {
  138. //TotalCount>0且Results集合不为空
  139. TotalCount = 1,
  140. Results = new List<ActivityBatchQueryItem>() { new ActivityBatchQueryItem() { Id = _wellTestingEmission.JobId } }
  141. }
  142. };
  143. _httpClientWrapperSvc.Setup(x => x.PostAsync<RequestBase<ActivityBatchQueryRequest>, ResponseBase<ActivityBatchQueryResponse>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityBatchQueryRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  144. .ReturnsAsync(activityBatchQueryResponse);
  145. _httpClientWrapperSvc.Setup(x => x.PutAsync<RequestBase<ActivityCreateUpdateRequest>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityCreateUpdateRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  146. .ReturnsAsync(_wellTestingEmission.JobId);
  147. var exception = await Record.ExceptionAsync(async () => await _sut.InsertOrUpdateActivityAsync(_fileMetadataId, _wellTestingEmission, _operationalActivity, _token));
  148. exception.Should().BeNull();
  149. }
  150. [Fact]
  151. public async Task InsertOrUpdateActivity_ShouldSuccess_WhenUpdate_Met401()
  152. {
  153. int calls = 0;
  154. ResponseBase<ActivityBatchQueryResponse> activityBatchQueryResponse = new ResponseBase<ActivityBatchQueryResponse>()
  155. {
  156. Data = new ActivityBatchQueryResponse()
  157. {
  158. //TotalCount>0且Results集合不为空
  159. TotalCount = 1,
  160. Results = new List<ActivityBatchQueryItem>() { new ActivityBatchQueryItem() { Id = _wellTestingEmission.JobId } }
  161. }
  162. };
  163. _httpClientWrapperSvc.Setup(x => x.PostAsync<RequestBase<ActivityBatchQueryRequest>, ResponseBase<ActivityBatchQueryResponse>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityBatchQueryRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  164. .ReturnsAsync(activityBatchQueryResponse);
  165. _httpClientWrapperSvc.Setup(x => x.PutAsync<RequestBase<ActivityCreateUpdateRequest>>(It.IsAny<string>(), It.IsAny<RequestBase<ActivityCreateUpdateRequest>>(), It.IsAny<string>(), It.IsAny<string>()))
  166. .ReturnsAsync(_wellTestingEmission.JobId)
  167. .Callback(() =>
  168. {
  169. calls++;
  170. if (calls == 1)
  171. {
  172. throw new HttpRequestException("", new Exception(), HttpStatusCode.Unauthorized);
  173. }
  174. });
  175. var exception = await Record.ExceptionAsync(async () => await _sut.InsertOrUpdateActivityAsync(_fileMetadataId, _wellTestingEmission, _operationalActivity, _token));
  176. exception.Should().BeNull();
  177. }
  178. private void InitOptions()
  179. {
  180. ReferencingServices referencingServices = new ReferencingServices()
  181. {
  182. DataPartitionId = "DataPartition-Id",
  183. FileServiceURL = "https://global.FileService.URL",
  184. ActivityServiceURL = "https://global.ActivityService.URL",
  185. ProcessStatusServiceURL = "https://global.ProcessStatusService.URL"
  186. };
  187. //IOptions<T>类型的变量通过Value属性来获取实际的参数值,所以这里要重写Value属性
  188. _referencingServices.Setup(x => x.Value).Returns(referencingServices);
  189. }
  190. private void InitServices()
  191. {
  192. //AnalyzerService中调用了ISauthService.GetToken(),不重写GetToken()则所有用到此方法的地方返回值都是null(返回值是string类型)
  193. _sauthService.Setup(x => x.GetToken()).ReturnsAsync(_token);
  194. }
  195. }
  196. }

五、总结

完成上边两个单元测试之后其余Services的处理也都大同小异,这里就不完全展示了。

不同公司对单元测试的定义多多少少会有些不同,这里探讨的是xUnit+Moq数据的方式,在此之前我也看过许多博主关于单元测试的文章,但大多写的比较简单,比如:测试的方法就是个加减乘除,Assert比较一下结果是否正确就结束了,这样的文章很难应用到项目中,我也是后来接触到单元测试才有幸整理出这么一套东西,如果对大家有所帮助请点赞、关注、评论支持下,谢谢。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/287004
推荐阅读
相关标签
  

闽ICP备14008679号