我有一个WebAPI控制器,它带有这样的参数对象:
public class InvoicesParameters : QueryStringParameters
{
public string InvoiceType { get; set; } = "P";
public bool Approved { get; set; } = false;
public string Region { get; set; } = null;
public string VendorCode { get; set; } = null;
}
控制器工作正常。我可以传递任何或所有参数并获得预期的结果。现在,我试图使用xUnit为此控制器添加一个单元测试。我尝试了几种不同的方法,但都失败了。
我的测试看起来像这样:
[Theory(DisplayName = "Get Invoices")]
[ClassData(typeof(InvoicesParametersTestData))]
public void GetInvoices_ShouldReturnInvoices(InvoicesParameters iparams)
{
var mockService = new Mock<IShopAPService>();
mockService.Setup(x => x.GetInvoices(iparams))
.Returns(GetSampleInvoices());
var controller = new InvoicesController(mockService.Object);
IHttpActionResult actionResult = controller.GetInvoices(iparams);
var contentResult = actionResult as OkNegotiatedContentResult<List<Invoice>>;
Assert.NotNull(contentResult);
Assert.NotNull(contentResult.Content);
Assert.Equal(3, contentResult.Content.Count);
}
private List<InvoiceDto> GetSampleInvoices()
{
List<InvoiceDto> output = new List<InvoiceDto>
{
new InvoiceDto
{
Id = 1,
VendorCode = "PFSATL",
VendorName = "PlantStone LLC",
Type = "I",
PONumber = "54P-00007365",
OrderId = "940817",
InvoiceType = "P",
InvoiceNumber = "DT1010816950",
InvoiceDate = Convert.ToDateTime("01/01/2020"),
InvoiceAmount = 2496.48M,
Region = "WEST",
ShopNumber = "16",
ApprovalDate = null,
Approver = null
},
new InvoiceDto
{
Id = 2,
VendorCode = "NATSLC",
VendorName = "National American Doodads",
Type = "I",
PONumber = "72P-00004838",
OrderId = "874566",
InvoiceType = "P",
InvoiceNumber = "123454321789",
InvoiceDate = Convert.ToDateTime("01/01/2020"),
InvoiceAmount = 457.88M,
Region = "WEST",
ShopNumber = "16",
ApprovalDate = null,
Approver = null
},
new InvoiceDto
{
Id = 3,
VendorCode = "BRIDG",
VendorName = "Bridgeport Soda",
Type = "I",
PONumber = "54P-0074865",
OrderId = "741258",
InvoiceType = "P",
InvoiceNumber = "987456",
InvoiceDate = Convert.ToDateTime("01/01/2020"),
InvoiceAmount = 74.99M,
Region = "WEST",
ShopNumber = "16",
ApprovalDate = null,
Approver = null
}
};
return output;
}
public class InvoicesParametersTestData
{
public static IEnumerable<InvoicesParameters> TestData
{
get
{
yield return new InvoicesParameters { InvoiceType = "P", Approved = false };
yield return new InvoicesParameters { InvoiceType = "P", Approved = true };
}
}
}
此模式不正确。我收到ClassData的编译时错误,必须指向有效的类。有一个更好的方法吗?或解决我所拥有的方法?
您的InvoicesParametersTestData
类应如下所示:
public class InvoicesParametersTestData : IEnumerable<object[]>
{
private readonly List<object[]> _testData = new List<object[]>
{
new object[]
{
new InvoicesParameters
{
InvoiceType = "P", Approved = false
},
new InvoicesParameters
{
InvoiceType = "P",
Approved = true
}
}
};
public IEnumerator<object[]> GetEnumerator() => _testData.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}