C# TestMethod - async <ActionResult> Index()

183 Views Asked by At

I am new to Unit Testing and relatively new to C# too. Not a great combination! I have looked at similar questions on this forum and tried solutions with no success. Within my Home Controller, I have defined the following method. How do I write a [MethodTest] for async Task <ActionResult>?

Home Controller

public async Task<ActionResult> Index()
{
    var userId = Request.IsAuthenticated ? HttpContext.User.Identity.GetUserId() : null;
    var thumbnails = await new List<ThumbnailModel>().GetPropertyThumbnailsAsync(userId);

    var count = thumbnails.Count() / 4;
    var model = new List<ThumbnailAreaModel>();
    for (int i = 0; i <= count; i++)
    {
        model.Add(new ThumbnailAreaModel
        {
            Title = i.Equals(0) ? "My Content" : string.Empty,
            Thumbnails = thumbnails.Skip(i * 4).Take(4)
        });
    }

    return View("Index", model);
}

[TestMethod()]
public void Index()
{
    // Arrange

    // Validate model state end

    // Act
    ViewResult result = HomeController.Index() as Task<ActionResult>;

    //Assert
    Assert.IsNotNull(result);
}

If anyone can help or point me in the right direction, I would be grateful.

1

There are 1 best solutions below

0
On

You can declare your TestMethod async

[TestMethod]
public async Task Index()
{
    // Arrange

    // Validate model state end

    // Act
    ViewResult result = await HomeController.Index();

    //Assert
    Assert.IsNotNull(result);
}