Reputation: 1003
I am trying to test the following method:
[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");
}
For the positive test case, I wrote the following code:
[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);
}
On line: Assert.Equal(title, result);
I am getting the following errors:
Argument 1: cannot convert from "GTL.Models.Books.GtlTitle' to 'string'
Argument 2: cannot convert from "Microsoft.AspNetCore.Mvc.IActionResult' to string
What is going wrong with my unit test? Why does is it expecting the objects to be of type string?
Upvotes: 0
Views: 759
Reputation: 236268
Controller action returns IActionResult
, but you are comparing it to Title
object. You should instead check if it's OkObjectResult
and validate it's value:
var result = controller.InsertTitle(title);
var okResult = Assert.IsType<OkObjectResult>(result);
Assert.Equal(title, okResult.Value);
Upvotes: 2