【发布时间】:2020-09-29 07:08:14
【问题描述】:
我是单元测试 (xUnit) 的新手,在为它编写测试时我不太确定如何使用此方法。
基本上我有一个名为 Label.cs 的类,在构造函数中我使用 DI 注入 2 个接口。
我还有一个 Get() 方法:
- 构造一个 XML 请求
- 删除所有无效字符
- 调用 API
- 从响应中读取标签信息
- 返回响应
是否可以为这样的方法编写测试?我知道我可以模拟依赖项,将它们传递给构造函数并使用 Moq 设置方法,但是如果我在 Get() 方法内有 4 或 5 个来自 ILabelValidation 的验证方法怎么办?我需要使用 Moq 设置所有这些方法吗?
public class Label
{
private readonly ICarrierService _carrierService;
private readonly ILabelValidation _validator;
public Label(int accountId, ICarrierService carrierService, ILabelValidation validator)
{
_carrierService = carrierService;
_validator = validator;
}
public override async Task<CreateShipmentResponse> Get(int accountId, Shipment shipment)
{
string xmlRequest = ConstructRequest(shipment);
// strip out any invalid characters inside the request
xmlRequest = _validator.InvalidCharacterValidation(xmlRequest);
// what if I have another method that I use from the ILabelValidation?
// _validator.ValidatePackageCount(3);
var stringContent = new StringContent(xmlRequest, Encoding.UTF8, "text/xml");
// make the API request
var shipmentResponse = await _carrierService.CreateShipment(dict, stringContent);
var stream = await shipmentResponse.Content.ReadAsStreamAsync();
Models.Label labelInfo = GetLabelInfo(stream);
var response = new CreateShipmentResponse();
response.labels = new List<string>();
if (!string.IsNullOrEmpty(labelInfo.Base64String))
response.labels.Add(labelInfo.Base64String);
return response;
}
}
【问题讨论】:
标签: c# unit-testing moq xunit