我具有以下用于编写单元测试的PATCH方法。
[HttpPatch("{id}")]
public IActionResult Patch(Guid id, [FromBody] JsonPatchDocument<QuoteDraft> patch) {
Global.AccessToken = Request.Headers["Authorization"];
var draft = new QuoteDraft();
var json = string.Empty;
try {
draft = quoteDraftRepository.GetQuoteDraftById(id);
if (draft == null) {
throw new ArgumentException($"Draft quote not found for id {id}");
}
QuoteDraft quoteDraft = null;
foreach (var item in patch.Operations) {
json = Convert.ToString(item.value);
var lineItem = JsonConvert.DeserializeObject<LineItem>(json);
quoteDraft = AddLineItem(draft, lineItem);
}
return StatusCode(StatusCodes.Status200OK, new QuoteDraftResponse {
Message = messageHandler.GetMessage(MessageType.All),
QuoteDraft = quoteDraft
});
}
下面是我的单元测试方法:
[testmethod]
public void patchtestmethod()
{
var jsonobject = new jsonpatchdocument<quotedraft>();
var quotedraft = new quotedraft
{
market = "noo",
program = "ils",
brochure = "2019",
season = "v1",
currency = "nok",
totalprice = 100,
};
var value = jsonconvert.serializeobject(quotedraft);
jsonobject.add("/lineitem/-", value);
quotecontroller.patch(it.isany<guid>(), jsonobject);
}
我收到如下屏幕截图所示的错误:
json补丁必须看起来像这样。
op: 'add',
path: '/lineItem/-',
value: {
destination: this.props.result.destination.code,
currency: this.props.result.currency.code,
sku: getSku(this.props.result.course.code, this.props.result.destination.code),
unitType: this.props.result.course.unitType,
startDate: format(this.props.result.startDate),
endDate: this.props.result.endDate,
quantity: this.props.result.numberOfWeeks.id,
category: 'Course',
language: 'NO',
departurePoint: this.props.result.departure ? this.props.result.departure.code : null,
description: this.props.result.course.description
},
请让我知道我想念的东西。
谢谢
答案 0 :(得分:0)
对于jsonobject.Add
,它使用Expression<Func<TModel, TProp>> path
来定义此操作的路径。
Model.cs
public class QuoteDraft
{
public string Market { get; set; }
public string Program
{
get; set;
}
public List<LineItem> LineItem { get; set; }
}
public class LineItem
{
public string Destination { get; set; }
public string Sku { get; set; }
}
代码
var jsonobject = new JsonPatchDocument<QuoteDraft>();
var quotedraft = new QuoteDraft
{
Market = "noo",
Program = "ils"
};
var lineItem = new LineItem
{
Destination = "D",
Sku = "S"
};
jsonobject.Add(q => q, quotedraft);
jsonobject.Add(q => q.LineItem, lineItem);
var value = JsonConvert.SerializeObject(jsonobject);