How to invoke a common coded web test method from GetRequestEnumerator()?

It’s a fact that coded web test methods give more flexibility to the developer, i.e. common code reuse. So let’s create a coded web test in whose GetRequestEnumerator() method you want to call a common method which tests some other requests. Let’s make it look as GetCommonRequests() in the example below:

public class AWebTest : WebTest
{
    private IEnumerator GetCommonRequests()
    {
        WebTestRequest req1 = new WebTestRequest("http://google.com");
        yield return req1;

        WebTestRequest req2 = new WebTestRequest("http://google.com");
        yield return req2;
    }

    public override IEnumerator GetRequestEnumerator()
    {
        WebTestRequest req = new WebTestRequest("http://google.com");
        yield return req;

        GetCommonRequests();
    }
}

You would expect to see three requests in the test result. You will see only one though…

Solution

The reason for that is you make a simple call to GetCommonRequests(), and you are not returning (with yield command) the actual value to the enumerator that holds WebTestRequests. Going forward, in main test method only one web request is added to the enumerator.

To make it working you need to call GetCommonRequests() in more sophisticated way:

public class AWebTest : WebTest
{
    private IEnumerator GetCommonRequests()
    {
        WebTestRequest req1 = new WebTestRequest("http://google.com");
        yield return req1;

        WebTestRequest req2 = new WebTestRequest("http://google.com");
        yield return req2;
    }

    public override IEnumerator GetRequestEnumerator()
    {
        WebTestRequest req = new WebTestRequest("http://google.com");
        yield return req;

        IEnumerator requests = GetCommonRequests();
        while (requests.MoveNext())
        {
            yield return requests.Current;
        }
    }
}

Only this way will there be three requests visible in the test result.

Previous Post
Next Post