MSTest, I receive result.status code 200 but the result.value is null

Viewed 89

I checked that result.Result is OkResultObject and its status is 200, but when I get result.Value, it's null. Did I make any mistakes?

[TestMethod]
public void GetArtById_WithExisting_ReturnExpectedItem()
{
  // arrange
  ItemDto expected = new ItemDto()
  {
    Id = random.Next(),
    Name = Guid.NewGuid().ToString()
  };
  serviceStub.Setup(service => service.GetItemById(It.IsAny<int>())).Returns(expected);
  var controller = new ItemsController(serviceStub.Object);
  // act
  var result = controller.GetItemById(random.Next());
  //assert
  result.Value.Should().BeEquivalentTo(expected, options => options.ComparingByMembers<ItemDto>());
}

The error:

    Error Message:
   Expected t to be PRODUCTSERVICE.API.Dtos.ItemDto
{
    Id = 892888091,
    Name = "68319208-3f5a-442d-954e-bc45dc7cfe48",
}, but found <null>.

With configuration:
- Use declared types and members
- Compare enums by value
- Compare tuples by their properties
- Compare anonymous types by their properties
- Compare records by their members
- Compare PRODUCTSERVICE.API.Dtos.ItemDto by its members
- Match member by name (or throw)
- Be strict about the order of items in byte arrays
- Without automatic conversion.
1 Answers

I found that I need to cast it to OkResultObject before getting the Value.

[TestMethod]
public void GetItemById_WithExisting_ReturnExpected()
{
  // arrange
  var expected = CreateRandomItem();
  serviceStub.Setup(service => service.GetItemById(It.IsAny<int>())).Returns(expected);
  var controller = new ItemsController(serviceStub.Object);
  // act
  var result = controller.GetItemById(random.Next());
  //assert
  result.Result.Should().BeOfType<OkObjectResult>();
  var ok = (OkObjectResult)result.Result;
  ok.Value.Should().BeEquivalentTo(expected, options => options.ComparingByMembers<ItemDto>());
}
Related