Assert.Equal xUnit 测试时无法转换错误

Assert.Equal can not convert error while xUnit testing

我正在尝试测试以下方法:

[Route("api/title")]
[HttpPost()]
public IActionResult InsertTitle([FromBody] GtlTitle gtlTitle)
{
    string pattern = "[0-9]*[-| ][0-9]*[-| ][0-9]*[-| ][0-9]*";
    Match m = Regex.Match(gtlTitle.ISBN, pattern, RegexOptions.IgnoreCase);
    if (m.Success)
    {
        try
        {
            return Ok(_gtlTitleRepository.InsertTitle(gtlTitle));
        }
        catch (Exception e)
        {
            return BadRequest();
        }
    }
    else
        return BadRequest("Could not match");

}

对于正向测试用例,我写了如下代码:

[Fact]
public void Insert_Title_When_ISBN_Valid()
{
    DateTime d = new DateTime(1999, 6, 1);
    var repositoryMock = new Mock<IGtlTitleRepository>();
    var title = new GtlTitle() { ISBN = "978-0-105-696", VolumeName = "vname", TitleDescription = "desc", PublicationDate = d, 
                                     AuthorID = 2, PublisherID = 2, TempID = 77774};
    repositoryMock.Setup(r => r.InsertTitle(title)).Returns(title);

    var controller = new TitleController(repositoryMock.Object);

    var result = controller.InsertTitle(title);
    Assert.Equal(title, result);
}

在线:Assert.Equal(title, result);我收到以下错误:

Argument 1: cannot convert from "GTL.Models.Books.GtlTitle' to 'string'

Argument 2: cannot convert from "Microsoft.AspNetCore.Mvc.IActionResult' to string

我的单元测试出了什么问题?为什么它期望对象是字符串类型?

控制器操作 returns IActionResult,但您将其与 Title 对象进行比较。您应该检查它是否是 OkObjectResult 并验证它的值:

var result = controller.InsertTitle(title);
var okResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(title, okResult.Value);