Reputation: 920
I've recently started working with .NET Core 3.1 after coming from a .NET background and just trying to get up to speed with Unit Testing an MVC controller in the new framework.
In .NET creating an MVC website used to give the option of adding a Unit Test project whereas Core doesn't; so I have followed some guides and have put this simple test together in MSTest for the HomeController
index view.
HomeController.cs:
public class HomeController : Controller
{
public IActionResult Index()
{
return this.View();
}
}
HomeControllerTests.cs:
[TestMethod]
public void WhenIndexIsExecutedAsyncThenContentShouldBeReturned()
{
// arrange
var httpContext = new DefaultHttpContext();
var controller = new HomeController()
{
ControllerContext = new ControllerContext
{
HttpContext = httpContext
}
};
var actionContext = new ActionContext
{
HttpContext = httpContext
};
// act
var result = controller.Index().ExecuteResultAsync(actionContext);
// assert
Assert.IsNotNull(result);
Assert.IsNull(result.Exception);
}
I get an error:
Value cannot be null. (Parameter 'provider')
And I do not know what is causing the error.
Upvotes: 2
Views: 1365
Reputation: 920
For the sake of what I was trying to achieve, i.e. a simple test to return the view with some content (the latter falling into an integration test) this code will suffice for the first test. My implementation was overly complicated on first attempt.
[TestMethod]
public void WhenIndexIsExecutedAsyncThenViewShouldNotBeNull()
{
// arrange
var controller = new HomeController();
// act
var result = controller.Index() as ViewResult;
// assert
Assert.IsNotNull(result);
}
Upvotes: 1