如何在不使用JsonFormatter的情况下在Json中使用输入参数测试Post

时间:2014-08-31 23:45:40

标签: c# rest unit-testing asp.net-web-api

如何在不使用对象的情况下在单元测试器中定义Json数据?

这可以定义一个对象,然后将其作为输入参数传递:

SRSWebAPI.Models.DeptsAndBelowRateInput objDeptsAndBelowRateInput = new DeptsAndBelowRateInput();
List<DeptIdModel> lstDept = new List<DeptIdModel>();
lstDept.Add(new DeptIdModel() {DeptId = "1234"});
lstDept.Add(new DeptIdModel() { DeptId = "1222" });

objDeptsAndBelowRateInput.DeptIdList = new List<DeptIdModel>();
objDeptsAndBelowRateInput.DeptIdList.AddRange(lstDept);


System.Net.Http.Formatting.MediaTypeFormatter jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();

using (HttpResponseMessage response = client.SendAsync(request).Result)
{
    var answ = response.Content.ReadAsAsync<DeptsAndBelowRate>();

    Assert.IsNotNull(answ);
    Assert.IsNotNull(answ.Result);
    //Assert.True(answ.Result);
}

但是,我更愿意只传递json数据而不引用一个对象,但以下内容不起作用:

var theContent2 = new StringContent(@"
   {""DeptsAndBelowRateInput"": {
    ""RequestName"": ""AspGroup"",
    ""ReportstoDeptAs"": ""Assigned"",
    ""TrendType"": ""LostWorkDayCaseRate"",
    ""BudgetMonth"": ""07"",
    ""BudgetYear"": ""2104"",
    ""BemsId"": ""123456"",
    ""EmailAddress"": ""XYZSupportEmail@acme.com"",
    ""DeptIdList"": {
      ""DeptId"": [
        ""2"",
        ""3"",
        ""4""
      ]
    }
  }
}");

var client = new HttpClient(Server);
var request = createRequest("api/DeptsAndBelowRate", "application/json", HttpMethod.Post, theContent2);

var client = new HttpClient(Server);
var request = createRequest("api/DeptsAndBelowRate", "application/json", HttpMethod.Post, theContent2);

    using (HttpResponseMessage response = client.SendAsync(request).Result)
    {
        var answ = response.Content.ReadAsAsync<DeptsAndBelowRate>();

        Assert.IsNotNull(answ);
        Assert.IsNotNull(answ.Result);
        //Assert.True(answ.Result);
    }
}

1 个答案:

答案 0 :(得分:0)

更改此内容:

var request = createRequest("api/DeptsAndBelowRate", "application/json", HttpMethod.Post, theContent2);

到此:

var request = createRequest<StringContent>("api/DeptsAndBelowRate", "application/json", HttpMethod.Post, theContent, jsonFormatter);

并使用此基本方法:

    // Creates an HttpRequestMessage which includes object content (e.g. Post)
    protected HttpRequestMessage createRequest<T>(string url, string mthv, HttpMethod method, T content, MediaTypeFormatter formatter) where T : class
    {
        HttpRequestMessage request = createRequest(url, mthv, method);
        request.Content = new ObjectContent<T>(content, formatter);

        return request;
    }

让它发挥作用......