Как издеваться над методами PATCH WebAPI с помощью MS Unit? - PullRequest
0 голосов
/ 14 декабря 2018

У меня есть следующий метод 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
    },

Пожалуйста, дайте мне знать, что мне не хватает.

Спасибо

1 Ответ

0 голосов
/ 17 декабря 2018

Для jsonobject.Add он принимает Expression<Func<TModel, TProp>> path, который используется для определения пути для этой операции.

  1. 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; }
    }
    
  2. Код

    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);
    
...