When testing webservices, you find that there common methods when GETting and POSTing to restful webservices. The common pattern is to open a connection, setting your headers (Adding Auth, etc…), downloading JSON string then finally deserializing. Woudn’t be great to just re-use these patterns and not worry about the object being serialized and deserialized? There’s many ways to do this and here’s 2 examples that I wrote at least for both GET and POST requests. Note that there are many variations for this. I could combine both into 1 method but let’s just split them for now.
For GET:
public static async Task<T> RequestGet<T>(string resturl) { using (var httpclient = new HttpClient()) { httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("<Auth>", ConfigurationManager.AppSettings["<AuthKey>"]); var response = await httpclient.GetAsync(resturl); responsecontent = await response.Content.ReadAsStringAsync(); var returnobject = JsonConvert.DeserializeObject<T>(responsecontent); return returnobject; } }
For POST:
public static async Task<T> RequestPost<T>(string jasonstringcontent,string resturl) { using (var httpclient = new HttpClient()) { var stringContent = new StringContent(jasonstringcontent); httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("<Auth>", ConfigurationManager.AppSettings["<AuthKey>"]); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await httpclient.PostAsync(resturl, stringContent); responsecontent = await response.Content.ReadAsStringAsync(); var returnobject = JsonConvert.DeserializeObject<T>(responsecontent); return returnobject; } }
To use these methods, you can call them directly or re-use them as reference from other helper methods, for example:
For GET:
public static List<SomeObject> GetObjects(string WebServicesurl) { var uri = String.Format("{0}queryparam?format=Json", WebServicesurl); Task<List<SomeObject>> response = RequestGet<List<SomeObject>>(uri); return response.Result; }
Now the actual Test Method would be:
[TestMethod] public void ValidateGetObjects() { List<SomeObject> allobjects = HelperClassWebApi.GetObjects(webservicesurl); Assert.IsTrue(allobjects .Count >= 5); Console.WriteLine("Test Case Passed for GetObjects"); }
For POST:
[TestMethod] public void ValidatGetUserAuthToken() { string jsonstringparams = "{ \"Password\": \"" + logoninfo.Password + "\", \"UserId\": \"" + logoninfo.Username + "\"}"; string uri = String.Format("{0}/authtoken?format=Json", webservicesurl); var clienttoken = HelperClassWebApi.RequestPost<AuthTokenResponse>(jsonstringparams, uri); Assert.IsTrue(!string.IsNullOrWhiteSpace(clienttoken.Result.MyAccountAuthToken)); Console.WriteLine("Test Case Passed for: customers/myaccount/authtoken"); }
Generics are awesome!