json - 如何使用 MS Unit 模拟 WebAPI 的 PATCH 方法?
问题描述
我有以下 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
},
请让我知道我错过了什么。
谢谢
解决方案
对于jsonobject.Add
,它接受Expression<Func<TModel, TProp>> path
用于定义此操作的路径。
模型.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);
推荐阅读
- java - 如何从活动中从 Recycleview 中删除项目
- android - 在 Firebase Robo 测试中选择帐户
- javascript - 带有过滤列表的多个下拉 Vue 组件
- git - 如何以编程方式验证我已在功能分支中正确地重新设置基础
- php - 日志一直记录“Http Analyzer failed”?
- django - Kubernetes 构建 django + uwsgi + nginx 显示失败(111:连接被拒绝)同时连接到上游
- heroku - 使用 webhook 密码的要点
- node.js - Express 路由器完全跳过中间件
- c - C中8位数字的算术运算过程
- python - 在 Python 中替换字符返回 TypeError: string operation on non-string array