C# 如何提取随ok一起发送的字符串以在单元测试中进行检查

C# 如何提取随ok一起发送的字符串以在单元测试中进行检查,c#,unit-testing,C#,Unit Testing,如何提取随ok一起发送的字符串以在测试中进行检查 public IHttpActionResult PostConnect() { try { return Ok(result.ToString()) } catch (Exception ex) { return BadRequest("An error"); } } 我试着做点什

如何提取随ok一起发送的字符串以在测试中进行检查

  public IHttpActionResult PostConnect()
    {
        try
        {
            return Ok(result.ToString())
        }
        catch (Exception ex)
        {
            return BadRequest("An error");
        }
    }
我试着做点什么,但没有成功

        [TestMethod]
    public void TestPostConnect()
    {
        var agentController = new Controller();
        IHttpActionResult actionResult = agentController.PostConnect();
        var okResult = actionResult as OkObjectResult;
    }

如何将字符串转换为json?

您不应该在测试中假设它是OkObjectResult,这是测试的主要原因。这意味着您应该期望它是OkObjectResult类型。之后,可以使用Value属性检索字符串

[TestMethod]
public void TestPostConnect()
{
    var agentController = new Controller();
    IHttpActionResult actionResult = agentController.PostConnect();
    var result = actionResult.Should().BeOfType<OkObjectResult>();
    result.Value.Should().BeOfType<string>();
    result.Value.Should().Be("your string");
}
[TestMethod]
public void TestPostConnect()
{
var agentController=新控制器();
IHttpActionResult actionResult=agentController.PostConnect();
var result=actionResult.Should().BeOfType();
result.Value.Should().BeOfType();
result.Value.Should().Be(“您的字符串”);
}

您不应该在测试中假设它是OkObjectResult,这是测试的主要原因。这意味着您应该期望它是OkObjectResult类型。之后,可以使用Value属性检索字符串

[TestMethod]
public void TestPostConnect()
{
    var agentController = new Controller();
    IHttpActionResult actionResult = agentController.PostConnect();
    var result = actionResult.Should().BeOfType<OkObjectResult>();
    result.Value.Should().BeOfType<string>();
    result.Value.Should().Be("your string");
}
[TestMethod]
public void TestPostConnect()
{
var agentController=新控制器();
IHttpActionResult actionResult=agentController.PostConnect();
var result=actionResult.Should().BeOfType();
result.Value.Should().BeOfType();
result.Value.Should().Be(“您的字符串”);
}

检查
属性?
它不工作
是一个相当宽泛的说法。它没有告诉我们实际发生的情况与预期的情况相符。请检查
属性?
它不工作
是一个相当宽泛的陈述。它并没有告诉我们实际发生的事情与预期相符。他在这行给我写了一个错误:“var result=actionResult.Should().BeOfType();”诱惑:IHttpActionResult不包含使用FluentAssertions添加的'Should'定义;在文件的顶部,并在csproj中添加对该文件的包引用。他在这一行给我写了一个错误:“var result=actionResult.Should().BeOfType();”诱惑:IHttpActionResult不包含使用FluentAssertions添加的'Should'定义;在文件的顶部,并在csproj中添加对该文件的包引用。