Creating a Request Payload in RestSharp using XML

I’m currently looking at building a test framework in c# utilising Restsharp. The payload I’m trying to create is outlined below

 <Order>
<BillingAddress>
    <AddressLine1></AddressLine1>
    <AddressLine2></AddressLine2>
    <City></City>

</BillingAddress>
<Items>
    <Item IsKit="false">
        <CountryVATRate></CountryVATRate>
        <Group></Group>
        <Reference></Reference>
     </Item>
    <Item IsKit="false">
        <CountryVATRate>0.25</CountryVATRate>
        <Group>5360693120</Group>
        <Reference>5360693120</Reference>
    </Item>
</Items>
<OrderAmount>35</OrderAmount>
<TimeStamp>2017-03-30 00:00:00.102</TimeStamp>

I was just after some advice on how I might construct this request in c# code so that I can then parameterise the values for my testing purposes. Specifically, I’m struggling with the nested ‘Items’ section where I may have multiple ‘Item’ blocks to add…how would I do this in code?

Hello @tilston1001!

One method is to define the payload using classes. Once everything is in a class, the program can serialize and deserialize into most any format.

For example, the Item might be defined as

public class Item()
{
double CountryVATRate;
int Group;
int Reference;
}

In the class defining the overall payload, a collection of Items might appear as this.

public class Order()
{
BillingAddress bAddr; //another class
List Items;
double OrderAmount;
DateTime TimeStamp;
}

Does that help?

Joe

1 Like

Hi Joe, this helps massively thank you!

Do you know of any sample test projects that are structured in this way e.g defining the payload using classes? I find a visual representation helps with my understanding. Or, alternatively, if you wouldn’t mind, based on your example above would you be able to provide a small example of how the test might be structured?

Andy

Hello Andy!

I don’t know of any sample test projects. Give me a couple days and I can craft one for you.

Joe

1 Like

That’s very kind, thanks Joe.

I just need a bit of a nudge to get me moving…I can visualise what I need to do, but I’m just having issue piecing it together!

Hello Andy!

Sorry for the delay! Here are the examples. I use Visual Studio 2017 Community for development. The NewtonSoft library is used for working with JSON. I included XML and JSON in this example.

The Order class:

namespace APIPayloadDemo
{
public class Item
{
public double CountryVATRate;
public int Group;
public int Reference;
}

public class BillingAddress
{
    public string AddressLine1;
    public string AddressLine2;
    public string City;
}


public class Order
{
    public BillingAddress bAddr;
    public List<Item> Items;
    public double OrderAmount;
    public DateTime TimeStamp;

    public Order()
    {
        Items = new List<Item>();
    }
}

}

Using the Order class to serialize and deserialize:

namespace APIPayloadDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Item item1 = new Item()
            {
                CountryVATRate = 1.23,
                Group = 5,
                Reference = 9445
            };

            Item item2 = new Item()
            {
                CountryVATRate = 2.34,
                Group = 8,
                Reference = 2006
            };

            BillingAddress billAddr = new BillingAddress()
            {
                AddressLine1 = "123 Main",
                City = "Springfield"
            };

            Order theOrder = new Order()
            {
                bAddr = billAddr,
                OrderAmount = 4.56,
                TimeStamp = DateTime.Now
            };

            theOrder.Items.Add(item1);
            theOrder.Items.Add(item2);

            //to JSON
            string jsonPayload = JsonConvert.SerializeObject(theOrder);
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.Write(jsonPayload);
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("");

            //to class from JSON
            Order newOrder = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(jsonPayload);

            //to XML
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            System.IO.MemoryStream strm = new System.IO.MemoryStream();
            XmlWriter writerA = XmlWriter.Create(strm, settings);

            XmlSerializer xsSubmit = new XmlSerializer(typeof(Order));
           
            xsSubmit.Serialize(writerA, theOrder);
            strm.Position = 0;

            System.IO.StreamReader reader = new System.IO.StreamReader(strm);
            string xmlPayload = reader.ReadToEnd();

            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.Write(xmlPayload);
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("");

            //to class from XML
            XmlSerializer serializer = new XmlSerializer(typeof(Order));
            Order resultOrder;
            using (TextReader txtReader = new StringReader(xmlPayload))
            {
                resultOrder = (Order)serializer.Deserialize(txtReader);
            }

            System.Diagnostics.Debug.WriteLine("Order Amount: " + resultOrder.OrderAmount.ToString());
        }
    }
}

Let me know how it goes!

Joe

1 Like

This is really helpful thank you Joe!

Just a couple of quick question:

  1. so you wouldn’t put Item, Items and BillingAddress into their own separate classes? You’d incorporate them all within the Order class? Was just trying to work out the reason behind this
  2. Could I run the Program class directly to execute the code to use for testing? I’m trying to understand how I would be able to grab the payload(in XML or JSON) and then use it to execute requests against the API

Andy

Hello Andy!

  1. I placed everything into the Order class because it appeared they were all a part of the payload used in the API. Item and BillingAddress are defined as separate classes. How might you mean “separate” classes?
    Note that the IsKit attribute is not in the payload - not sure how to model an attribute. In this case, it could be another property of Item.

  2. Sorry for not making this clearer. I placed examples of how construct the payload (comments “to JSON” and “to XML”) and how to extract the payload to a class (comments “to class from JSON” and “to class from XML”).
    If you post to the API, use the string created in the construction (jsonPayload or xmlPayload). If you receive a response from the API in the form of Order, deserialize response using the deserialize examples.
    When you say “grab the payload”, I understand you are receiving Order as a payload from the API. If that is the case, I recommend the deserialize examples. In my opinion, you want to extract relevant code from Program.cs for testing.

Does that help?

Joe

1 Like

Thank you again Joe, this helps massively with my understanding.

Apologies if my questions seem basic by the way, bit of a learning curve for me on this

Andy

Hello Andy!

You’re welcome! Your questions are great and I encourage lots of questions (that’s what QA stands for: Question Asker - at least that’s one definition).

Joe

1 Like

I think what this has highlighted is that I possibly need to go back to basics and go through some of my “c# basics” courses/books.

However, I often have the quandary as to how much of a technical programmer I need to be as an automation tester. I’d be interested to here your thoughts on this?

Hello Andy!
Great topic! I think asking yourself this puts you on a great path to have your testing side and your technical side collaborate so that you provide the maximum assistance to testers as possible. I apologize and thank you for reading my lengthy reply in advance.

When our organization established a job family (known as a System Test Engineer) for this kind of work, there were some developers already creating and maintaining automation, and some who wanted to try it. At the time, creating automation did not have many constraints so, in my opinion, many developers took advantage of this.
They created lots of automation and a few frameworks. Not all of it was useful to testing teams. Further, those same developers spend way too much time maintaining automation that should have been, in my opinion, more simply implemented. In some cases, the maintenance is all they do just to keep pace with changes to the products that are evaluated with automation. This does not serve testing teams well.
Lastly, some of the developers have little or no background in testing. Without a testing foundation (and some time spent just testing), automation becomes, in my opinion, little more than a technical pursuit to demonstrate technical prowess. I’m usually underwhelmed and decidedly unimpressed with these kinds of efforts.

There are also people who are testers and want to move into the System Test Engineer job family. They must learn, as you have mentioned, some programming in order to work with various tools. They are, in my opinion, more successful because of the testing foundation. They bring a certain economical view to the problem: What is the right number of tests? Is automation the right solution for the problem? This is how they are taught, this is how they have worked, and these questions are profoundly appropriate when considering automation solutions.

Today, this job family is more than automation because testing is more than running tests. System Test Engineers assess product testability and assist Project Test Leads in advocating for testability improvements. System Test Engineers participate early in projects to assess testability, review test environments, and review opportunities for utilities and automation. This assessment also aids the Test Lead in planning the test strategy so the testing team can support the pace of development and maintain high quality.
It required some time to reach this level of participation and collaboration. I invite you to pursue your technical interests and assist testing teams with great automation (APIs are a great place to start!). I challenge you to keep an eye out for test engineering opportunities mentioned above.

You mentioned that you might remediate a little. Cool! I do that also if I’ve been away from a tool or technology. Embrace it! At some point, you’ll have examples that you can use and build on.
More importantly, treat every opportunity as an experiment. It doesn’t have to be perfect the first time or even the second time. In the end, your solution has to provide valid results in a timely manner. That might occur somewhere between “got it working” and “perfection”. Perfection, in my experience, costs too much; there is a satisfactory middle ground. If you didn’t like the outcome, make a list of what you would do better and try it on the next project (or next experiment).

How much technical programming knowledge is needed to write automation? You need to understand how to use the basics of programming (e.g., assignment, iteration, decision, input/output, math) to construct solutions. I think it will be important to understand methods of program and data organization (e.g., object oriented design).
Languages will provide their benefits in various flavors of syntax. For example, the introduction of generics in C# is a wild application of the basics and we are all the better for it.
I think you are discovering how much you need for your position or pursuit. When you needed help, MoT and many other resources are available to assist. The lure of having a working program or automation suite pales in comparison to the preparation required to make it useful and maintainable. Research and experimentation has helped me. If the concept is new, I create a sandbox project in Visual Studio and use it help me learn. Things that don’t compile, or that don’t execute correctly are teachers not errors!

Lastly, I encourage you to seek opinions of others. One notable person is Angie Jones (@techgirl1908 on Twitter and MoT) writes and speaks on automation. I especially enjoyed her recent article on automation.

Thanks again!
Joe

2 Likes

Thanks Joe, I take a lot away from what you have written there and appreciate the time you’ve taken out to offer guidance!

Andy