How can I test WCF JSON services. I want to create something like unit tests for this services. Is there any tutorial for something like this? I would b most interested to write the JSON object myself like {somedata:abc,foo:boo}
1 Answer
Here is a link that might get you started.
http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests
"-create a dynamic class that matches JSON datastructure -Serialize it to JSON -Send json to web service -Deserilize response to a dynamic object -Make sure that response has value that I expected"
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}&value2={2}&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"]);
}