简体   繁体   English

如何提取用 ok 发送的字符串以在单元测试中检查它

[英]How can I extract the string sent with the ok to check it in unit test

How can I extract the string sent with the ok to check it in test如何提取用 ok 发送的字符串以在测试中检查它

  public IHttpActionResult PostConnect()
    {
        try
        {
            return Ok(result.ToString())
        }
        catch (Exception ex)
        {
            return BadRequest("An error");
        }
    }

I tried to do something but it didn't work我试图做某事,但没有奏效

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

And how can I convert from string to json?以及如何从字符串转换为 json?

You shouldn't assume in your test that it is an OkObjectResult, that's the main reason for tests.你不应该在你的测试中假设它是一个 OkObjectResult,这是测试的主要原因。 Meaning you should expect it to be of type OkObjectResult.这意味着您应该期望它是 OkObjectResult 类型。 After that you can use the Value property to retrieve the string.之后,您可以使用 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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