Lately, we've been playing around a lot with WCF. Unit testing WCF services is not exactly challenging (well done Microsoft), but it seems that with unit tests it is quite difficult to test certain behaviour, for example, authentication or authorization. There are other means of developing automated tested system tests, but they are not that easy to find and can usually be run only on the actual deployment server (or everybody has to have installed software on their machines). This is just a lot of work.
Instead, we propose to do a little bit of a hack - reuse unit testing features in Visual Studio to send and receive responses from the server. Unfortunately, VS doesn't allow to run unit tests and server at the same time, so you will need two instances of visual studio. In the first instance, run your project and in the second run your tests.
In your solution, create a new Unit Testing projest. Below you can find an example test method which sends a request to the server and gets a response. The aim is to verify the behaviour of your service. The test is divided into 2 parts: sending the request and getting the response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
[TestMethod] public void InvokePOSTService() { // SENDING REQUEST var addRequest = new { data = "sometest data" }; var request = (HttpWebRequest)WebRequest.Create("http://localhost:81/Service.svc/DoWork"); 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(); // Getting the RESPONSE var httpWebResponse = (HttpWebResponse)request.GetResponse(); string jsonString; using (var sr = new StreamReader(httpWebResponse.GetResponseStream())) { jsonString = sr.ReadToEnd(); } var jsonAddResponse = jsSerializer.Deserialize(jsonString); //This is my own DataContract Assert.AreEqual(jsonAddResponse["Status"], 0); } |