【发布时间】:2020-02-06 22:01:32
【问题描述】:
我正在尝试将 4 个几乎相同的测试用例转换为一个,其中一个使用 xUnits InlineData。
问题在于,我想要区别的参数是一个长字符串——实际上是一个带有微小变化的 JSON-“字符串”。它是这样的(我只取了相关的):
....
....
var mockHttp = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHttp
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent( // the below part is the only thing that differs
"{'content':[" +
"{'Id':'00001', 'eNumber':'001', 'isOwner': true, 'isAlone':false}," +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"]}"
)
})
.Verifiable();
var httpClient = new HttpClient(mockHttp.Object)
{
BaseAddress = new Uri("http://something.com/")
};
下一个测试包含相同的内容,但带有另一个“内容”,如下所示:
....
....
"{'content':[" +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"{'Id':'00001', 'eNumber':'002', 'isOwner': false, 'isAlone':true}," +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"]}"
....
....
第三个是这样的:
....
....
"{'content':[" +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':false}," +
"{'Id':'00001', 'eNumber':'no', 'isOwner': false, 'isAlone':true}," +
"{'Id':'00001', 'eNumber':'007', 'isOwner': true, 'isAlone':true}," +
"{'Id':'00001', 'eNumber':'003', 'isOwner': false, 'isAlone':false}," +
"]}"
....
....
以此类推,接下来是两个。 所以我想知道是否有一种聪明的方法可以将 5 种类型的内容作为参数放入 InlineData 中 - 从而以某种方式节省大量复制的代码?可能有,但我仍然没有弄清楚怎么做,反正没有写很多代码。
将测试编写为 5 个单独的测试全部变为绿色,因此我唯一要寻找的是一种更智能的代码编写方式,只需更改 StringContent 中的参数/字符串即可使其更简洁、更易于阅读。
根据 cmets 中的问题更新:
我正在测试的课程是这样的:
....
....
var httpResponseMessage = await User(// something);
if (!httpResponseMessage .IsSuccessStatusCode) return;
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var deserializedContent = JsonConvert.DeserializeObject<UserModel>(content); // it fails here...
....
....
我的 UserModel 类如下所示:
public class UserModel
{
public UserModelDto[] {get; set;}
}
我的 UserModelDto 类看起来像这样:
public class UserModelDto
{
public string Id{ get; set; }
public string ENumber { get; set; }
public bool IsOwner { get; set; }
public bool IsAlone { get; set; }
}
【问题讨论】:
-
您可以创建一个模型来保存数据并使用
MemberDataAttribute来使用IEnumerable<object[]>作为您的测试源,其中该测试源的元素是您的对象模型的数组。在测试中,您可以将这些对象序列化为字符串。
标签: c# json testing serialization xunit