【问题标题】:Evaluating boolean expression stored in string with Roslyn使用 Roslyn 评估存储在字符串中的布尔表达式
【发布时间】:2018-04-12 16:56:48
【问题描述】:

目前我正在为一个应用程序做一些集成测试,这种情况存储在一个json文件中,单元测试的断言部分也存储在那个json中,所以我需要解析该字符串为布尔值或其他内容。

我已经尝试过 Roslyn,但我无法让它工作,它抛出了这个异常:

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

带case的json文件是这样的:

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

尝试过这样的事情:

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

尝试了小写,大写,与创建的类相同的样式,仍然无法正常工作。

解决方案源代码是here,也许你可以在那里获得更多信息。

编辑:上面解释的代码所在的文件是here

【问题讨论】:

  • @CamiloTerevinto 已编辑,谢谢。
  • 你不能像这样直接与局部变量交互;您必须将它们显式地暴露给脚本。

标签: c# roslyn roslyn-code-analysis


【解决方案1】:

使它与 Globals 类一起工作。

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

然后在测试中传递参数,就像@SLaks 在 cmets 中所说的那样:

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

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

希望这对某人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多