2

I'm looking at implementing a runsettings file for automated testing. Thing is, my variables are complex objects, and all I can find in the documentation about runsettings has simple key/value options, like so.

<TestRunParameters>
  <Parameter name="webAppUrl" value="http://localhost" />
  <Parameter name="docsUrl" value="https://learn.microsoft.com" />
</TestRunParameters>

I'm wondering if it's possible to specify a complex object like you might specify below (especially since TextContext.Properties returns an object, so I assume it's polymorphic in some sense?) and cast it to a given defined class

<TestRunParameters>
  <Parameter name="AdminUser" UserID="Admin" Password="P@55w0rd!" />
  <Parameter name="User" UserID="User" Password="P@55w0rd!" />
</TestRunParameters>

I realize I can do the below and manually create my object instances, but I'd really really like to avoid it if at all possible

<TestRunParameters>
  <Parameter name="AdminUserID" value="Admin"/>
  <Parameter name="AdminUserPW" value="P@55w0rd!" />
  <Parameter name="UserID" value="User"/>
  <Parameter name="UserPW" value="P@55w0rd!" />
</TestRunParameters>

1 Answer 1

0

As long as I know, it's impossible at the moment. However, there are two options:

  1. store your serialized data in json file(s); add a single parameter with name of the json file into your runsettings TestRunParameters section; and deserialize json

    e.g. <Parameter name="Environment" value="appsettings.Staging.json" />

    But in this case, you can consider using appsettings.json instead.

  2. if a linear class would be enough for your needs, the following method helps to avoid reading all parameters one by one. e.g.

    public class GlobalTestSettings
    {
        public string param1;
        public int param2;
    }
    
    private static void DeserializeTestRunParameters(TestContext context)
    {
        //Get GlobalTestSettings data from {Environment}.runsettings
        var typeGlobal = typeof(GlobalTestSettings);
        foreach (var property in typeGlobal.GetProperties())
        {
            if (property.CanWrite)
            {
                var propertyName = property.Name;
                var propertyValue = context.Properties[propertyName];
                var propertyValueStr = propertyValue?.ToString();
                Console.WriteLine($@"Set TestRunParameter '{propertyName}' = '{propertyValueStr}'");
    
                if (!string.IsNullOrEmpty(propertyValueStr))
                {
                    property.SetValue(typeGlobal, Convert.ChangeType(propertyValue, property.PropertyType), null);
                }
            }
        }
    }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.