2

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 1

3

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}&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"]);
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.