2

I have this C# code for my unit test and it has syntax error at result as OkObjectResult

Task<IActionResult> result = controller.Create(Id);

var okObjectResult = result as OkObjectResult;

How to I convert from type 'System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>' to 'Microsoft.AspNetCore.Mvc.OkObjectResult'?

4
  • 2
    Can you try var okObjectResult = result.Result as OkObjectResult;? Commented Oct 27, 2020 at 2:34
  • IActionResult result = await controller.Create(Id); Commented Oct 27, 2020 at 2:37
  • @Enigmativity, thanks. It works. Commented Oct 27, 2020 at 2:42
  • The type Task<T> and OkObjectResult are two unrelated types with root type object as the only common ancestor. The actual problem should be about how to get and convert the result of a Task<T> object to another type, as above comments suggest. Commented Oct 27, 2020 at 3:06

2 Answers 2

5

First of all make sure that OkObjectResult implements IActionResult. The important thing is however is to take note that you can not convert directly between a Task of said class to a Concrete type of said class. In your case you have Task<T>, you can not directly convert it to a type of it generic argument directly. In the comments @Enigmativity suggests that you get Task.Result as OkObjectResult. Even though it should work, it may end up with deadlocks (I see that you are working on .net core which does not have synchronization context therefore not likely to end up in a deadlock).

My advice is to go async all the way.

var result = await controller.Create(Id);
var okObjectResult = result as OkObjectResult;
Sign up to request clarification or add additional context in comments.

Comments

3

try to add async to method and await before _controller solved my same issue

Comments

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.