Search code examples
c#visual-studio-2013webtest

how to get the response body in code webtest?


I wrote a webtest that calls a web-service.

I want to get the response body and do some validation on it.

    public override IEnumerator<WebTestRequest> GetRequestEnumerator()
    {


        WebTestRequest request2 = new WebTestRequest("webservice");

        request2.Headers.Add("Content-Type", "application/json");
        request2.Method = "POST";
        request2.Encoding = System.Text.Encoding.GetEncoding("utf-8");
        StringHttpBody request2Body = new StringHttpBody();

        request2Body.ContentType = "application/json";
        request2Body.InsertByteOrderMark = false;
        request2Body.BodyString = @"{                                       <body>}";
        request2.Body = request2Body;


        WebTestResponse res = new WebTestResponse();
        console.WriteLine(res.BodyBytes);

       yield return request2;

       request2 = null;
    }

When i ran the above code i didn't get any response on my console.

How can i get the response body using coded webtest?


Solution

  • There are at least three problems with the code in the question

    1. The code in the question does not perform the request before doing the WriteLine. The two statements WebTestResponse res = new WebTestResponse(); and console.WriteLine(res.BodyBytes); just create a new WebTestResponse object (with all default values) and then try to print part of its contents. The request is issued by the code that calls your GetRequestEnumerator method.

    2. The console object is not defined. The normal console has a first letter uppercase, ie Console.

    3. When a web test executes I am not sure where its "console" output will go. The standard output of a web test is not, as far as I know, a well defined thing.

    An easy way to get at the response body is to use the PostRequest method of a WebTestRequestPlugin. For a start

    public class BodyContentsDemo : WebTestRequestPlugin
    {
        public override void PostRequest(object sender, PostRequestEventArgs e)
        {
            byte[] bb = e.Response.BodyBytes;
            string ss = e.Response.BodyString;
    
            e.WebTest.AddCommentToResult(
                "BodyBytes is " +
                bb == null ? " null"
                : bb.Length.ToString() + " bytes");
    
            e.WebTest.AddCommentToResult(
                "BodyString is " +
                ss == null ? "null"
                : ss.Length.ToString() + " chars");
    
            // Use bb or ss.
        }
    }
    

    Note the use of AddCommentToResult to provide logging information to the web test results log.