简体   繁体   中英

C# TestMethod - async <ActionResult> Index()

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM