2
如何測試WCF JSON服務。我想爲這個服務創建類似單元測試的東西。有沒有這樣的教程?我會最感興趣的是自己編寫JSON對象,如 {somedata:abc,foo:boo}如何測試WCF JSON服務 - 單元測試
如何測試WCF JSON服務。我想爲這個服務創建類似單元測試的東西。有沒有這樣的教程?我會最感興趣的是自己編寫JSON對象,如 {somedata:abc,foo:boo}如何測試WCF JSON服務 - 單元測試
這裏是一個可能讓你開始的鏈接。
http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests
「-create是JSON數據結構 與之匹配-Serialize以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}&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"]);
}
工作很好。謝謝 – Ryan 2012-04-25 18:20:36