简体   繁体   中英

Evaluating boolean expression stored in string with Roslyn

Currently I'm doing some integration testing for an app and such cases are stored in a json file, the assert part of the unit test is also stored in that json , so I need to parse that string to boolean or something.

I've tried with Roslyn but I can't make it work, it is throwing this exception:

Microsoft.CodeAnalysis.Scripting.CompilationErrorException: (1,1): error CS0103: The name 'entry' does not exist in the current context

The json file with the case looks like this:

  "entries": [
    {
      "name": "SayHello",
      "request": {
        "text": "Hello",
        "id": "61hacck8j6jg"
      },
      "response": {
        "text": "Hello",
        "id": "47me557ikbf7"
      },
      "assert": "Entry.Request.Text == Entry.Response.Text"
    }
  ]

Tried with something like this:

object result = await CSharpScript.EvaluateAsync("entry.Request.Text == entry.Response.Text");

Tried with lowercase, uppercase, same style as the class created, still not working.

Solution source code for this is here , maybe you can get more information there.

Edit: the file where the code explained above is here

Made it work with a Globals class.

public class Globals
{
    /// <summary>
    /// ExpectedResponse
    /// </summary>
    public Activity Request;
    /// <summary>
    /// ReceivedResponse
    /// </summary>
    public Activity Response;
}

Then in the test you pass the parameters, kinda how @SLaks said in the comments:

/// Arrange
var globals = new Globals { Request = entry.Response, Response = latestResponse };

/// Assert
Assert.IsTrue(await CSharpScript.EvaluateAsync<bool>(entry.Assert, globals: globals));

Hopefully this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM