如何测试WCF JSON服务 - 单元测试

时间:2012-04-23 16:25:41

标签: json wcf unit-testing

如何测试WCF JSON服务。我想为这些服务创建类似单元测试的东西。是否有类似这样的教程?我最感兴趣的是自己编写JSON对象 {somedata:ABC,FOO:嘘声}

1 个答案:

答案 0 :(得分:3)

这是一个可以帮助您入门的链接。

http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests

“ - 创建一个与JSON数据结构匹配的动态类 - 将其转换为JSON - 发送json到Web服务 -Deserilize对动态对象的响应 - 确保响应具有我预期的价值“

POST

[Test]
public void Add_WhenMethodPost_And_ValidApiKey_ReturnsSum()
{
var addRequest = new
{
    Value1 = 5,
    Value2 = 11,
    ApiKey = Const.ValidApiKey
};

var url = string.Format("{0}/json/add", Const.WebServiceUrl);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

var jsSerializer = new JavaScriptSerializer();
var jsonAddRequest = jsSerializer.Serialize(addRequest);

var writer = new StreamWriter(request.GetRequestStream());
writer.Write(jsonAddRequest);
writer.Close();

var httpWebResponse = (HttpWebResponse)request.GetResponse();

string jsonString;
using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
    jsonString = sr.ReadToEnd();
}

var jsonAddResponse = jsSerializer.Deserialize<dynamic>(jsonString);

Assert.AreEqual(16, jsonAddResponse["Sum"]);
}

GET

[Test]
public void Add_WhenMethodGet_And_ValidApiKey_ReturnsSum()
{
 var url = string.Format("{0}/json/add?value1={1}&amp;value2={2}&amp;apiKey={3}", Const.WebServiceUrl, 5, 11,
                         Const.ValidApiKey);
 var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
 httpWebRequest.Method = WebRequestMethods.Http.Get;
 httpWebRequest.Accept = "application/json";

 string jsonString;
 var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

 using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
 {
     jsonString = sr.ReadToEnd();
 }

 var jsSerializer = new JavaScriptSerializer();
 var jsonAddResponse = jsSerializer.Deserialize<dynamic>(jsonString);

 Assert.AreEqual(16, jsonAddResponse["Sum"]);
 }