Reputation:
I am using ASP.NET Core 2 WebAPI, xUnit, Moq.
I have a problem. I was trying the solution from this answer and this answer. Other found answers seem to be similar to these two.
With both mentioned approaches we are using casting of the IActionResult result
object to ObjectResult
or OkObjectResult
.
The main problem with my project is that after casting object result is null
.
Test method:
[Fact]
public async Task Post_CalledWithDefaultSetup_CallsAllMethods()
{
//default setup arranged in the ctor
IActionResult result = await _controller.Post();
var okResult = result as ObjectResult;
Assert.Equal(StatusCodes.Status200OK, okResult.StatusCode);
}
And tested method:
[HttpPost]
public async Task<IActionResult> Post()
{
//do some logic here
return StatusCode((int)HttpStatusCode.OK); //debug hits this
}
Also in my test class ctor
I am arranging my mocks and ControllerContext:
_serializationServiceMock.Setup(s => s.UnzipData(_array))
.Returns(_jsonExample);
_serializationServiceMock.Setup(s => s.DeserializeDataFromJson(_jsonExample))
.Returns(_listPersonModel);
var stream = new MemoryStream(_array);
var httpContext = new DefaultHttpContext();
httpContext.Request.Body = stream;
httpContext.Request.ContentLength = stream.Length;
var controllerContext = new ControllerContext()
{
HttpContext = httpContext,
};
_controller = new DataController(_repositoryMock.Object, _serializationServiceMock.Object) { ControllerContext = controllerContext };
Upvotes: 3
Views: 6247
Reputation: 4354
In your code block, the controller method returns StatusCodeResult
type. But you try to cast it to ObjectResult
. That's why you get null.
You can solve this in 2 ways;
1 -) You can use return Ok()
instead of return StatusCode(...)
so your controller method will return OkResult
and with parametered call Ok(someObj)
it will return OkObjectResult
.
2 -) you can cast Post result to StatusCodeResult
instead of ObjectResult
since your endpoint returns status code result like below.
var okResult = result as StatusCodeResult;
Upvotes: 4