问题
I'm using MStest for testing my controllers.
I want to test this action:
[HttpGet(Name = "GetGroups")]
public async Task<IActionResult> Get()
{
var groups = await _unitOfWork.Repository<Groupe>().GetAllAsync();
var groupsDto = Mapper.Map<IEnumerable<GroupDto>>(groups);
if (groupsDto.Count() == 0)
{
return NotFound();
}
return Ok(groupsDto);
}
One of the test for this action looks like that:
[TestMethod]
public async Task Group_Get_Should_Return_InstanceOfTypeOkNegotiatedContentResultIEnumerableGroupDto()
{
// Arrange
moqGroupRepository.Setup(g => g.GetAllAsync(null)).ReturnsAsync(groups).Verifiable();
moqUnitOfWork.Setup(x => x.Repository<Groupe>()).Returns(moqGroupRepository.Object);
var controller = new GroupController(moqUnitOfWork.Object);
// Act
var actionResult = await controller.Get() as OkNegotiatedContentResult<IEnumerable<GroupDto>>;
// Assert
Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<IEnumerable<GroupDto>>));
}
The problem here is OkNegotiatedContentResult is unknown in ASP.Net Core project test.
What should I use to test Ok() result?
回答1:
The probleme here is OkNegotiatedContentResult is unknow in asp net core project test What should i use to test Ok() result?
You could fix the problem by installing Microsoft.AspNetCore.Mvc NuGet package where implementations of IActionResult are defined.
However ASP.NET Core does not contain OkNegotiatedContentResult type, it's from ASP.NET Web API. In ASP.NET Core Controller.Ok() method returns the instance of OkObjectResult type.
You also have inconsistent checks in these two statements:
var actionResult = await controller.Get() as OkNegotiatedContentResult<IEnumerable<GroupDto>>;
Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<IEnumerable<GroupDto>>));
as operator will return null if object could not be cast to requested type. So you could replace the second check with the following:
Assert.IsNotNull(actionResult);
So the required steps are:
- Install
Microsoft.AspNetCore.MvcNuGet package to your Test project. Adjust the test code in the following way:
// ... using Microsoft.AspNetCore.Mvc; [TestMethod] public async Task Group_Get_Should_Return_InstanceOfTypeOkNegotiatedContentResultIEnumerableGroupDto() { // Arrange moqGroupRepository.Setup(g => g.GetAllAsync(null)).ReturnsAsync(groups).Verifiable(); moqUnitOfWork.Setup(x => x.Repository<Groupe>()).Returns(moqGroupRepository.Object); var controller = new GroupController(moqUnitOfWork.Object); // Act var actionResult = await controller.Get() as OkObjectResult; // Assert Assert.IsNotNull(actionResult); Assert.IsInstanceOfType(actionResult.Value, typeof(IEnumerable<GroupDto>)); }
来源:https://stackoverflow.com/questions/49507634/how-to-test-ok-result-using-mstest-in-asp-net-core-project