1

I'm trying to check the HttpStatusCode from a call to the controller but I can't figure out how to convert my ActionResult<T> to HttpStatusCodeResult.

Method from the controller :

[Get]
public async Task<ActionResult<PagedResult<PersoDemandLiteResponse>>> GetDemandsByFilterAsync([FromQuery] DemandFilterRequest filter)
    => await this.GetAsync(() => DemandService.GetDemandByFilterAsync(filter), (sources) => sources);

Here is my test method (simplified) :

... mocking of the services ...

var controller = new DemandController(demandService, organizationService.Object, productService.Object, Mapper.Object);

var request = new DemandFilterRequest { OrganizationId = Guid.NewGuid() };

var result = await controller.GetDemandsByFilterAsync(request);

//I would like to do something like this 
 var action = result as HttpStatusCodeResult;
 var badRequest = (int)HttpStatusCode.BadRequest;

 Assert.Equal(badRequest, action.StatusCode);

But I get the following error :

Error CS0039 Cannot convert type 'Microsoft.AspNetCore.Mvc.ActionResult>' to 'System.Web.Mvc.HttpStatusCodeResult' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.

Any idea on how to achieve this ?

0

1 Answer 1

4

Assuming the method under test returns a bad request as implied by the example code, that would have been something similar to

//...

if(...)
    return BadRequest();

//...    

Then when unit testing, the wrapped result needs to be extracted from the action result

//Arrange
//...omitted for brevity

//Act
ActionResult<PagedResult<PersoDemandLiteResponse>> response = 
    await controller.GetDemandsByFilterAsync(request);
    
//Assert
BadRequestResult actual = response.Result as BadRequestResult;    
Assert.NotNull(actual);
int badRequest = (int)HttpStatusCode.BadRequest;
Assert.Equal(badRequest, actual.StatusCode);

Reference Controller action return types in ASP.NET Core Web API

Sign up to request clarification or add additional context in comments.

1 Comment

Great, I didn't how to manage to use it like this and yes, the method returns a bad request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.