Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# async Task - Unit testing

I am new to C# unit testing and have to test if the method is working properly.

Here is what I have so far:

  public async Task<IHttpActionResult> Post(API_FIRM_LINK aPI_FIRM_LINK)
    {
        db.API_FIRM_LINK.Add(aPI_FIRM_LINK);
        await db.SaveChangesAsync();

        return Created(aPI_FIRM_LINK);
    }

test method: Not really sure if I am on the right path If someone could provide an example based on my test

     public async Task PostTest()

    {
        ////Arrange
        API_FIRM_LINKController controller = new API_FIRM_LINKController();

        API_FIRM_LINK aPI_FIRM_LINK = null;

        IHttpActionResult expectedResult = await controller.Post(aPI_FIRM_LINK);
        //act

        IHttpActionResult result = await controller.Post(API_FIRM_LINK, aPI_FIRM_LINK);


        ////Assert
        IComparer<IHttpActionResult> comparer = new IHttpActionResultComparer();
       // Assert.IsTrue(comparer.Equals(expectedResult, result));

        Assert.IsNotNull(result);
        Console.Write(result);
like image 603
usertestREACT Avatar asked Oct 19 '25 02:10

usertestREACT


1 Answers

If you use a modern version of Microsoft.VisualStudio.TestTools.UnitTesting you can use an async test method, like you do in your question.

If you want to Test whether your Post function returns the expected data, do the following:

[TestMethod()]
public async Task PostTestAsync()
{
    var controller = new API_FIRM_LINKController();
    // TODO: do some preparations, so you can expect a specific return value
    IHttpActionResult expectedResult = ...

    // call PostAsync and await for it to finish
    Task taskPost =  controller.PostAsync(API_FIRM_LINK, aPI_FIRM_LINK);
    IHttpActionResult result = await taskPost;

    // of course this can be done in one line:
    IHttpActionResult result = await controller.PostAsync(API_FIRM_LINK, aPI_FIRM_LINK);

    // compare whether result equals expectedResult
    // for example: create a class that implements IComparer<IHttpActionResult>
    IComparer<IHttpActionResult> comparer = new IHttpActionResultComparer();
    Assert.IsTrue(comparer.Equals(expectedResult, result);
}

If you use a test suite where you can't use async tests:

[TestMethod()]
public void PostTest()
{
    var controller = new API_FIRM_LINKController();
    IHttpActionResult expectedResult = ...

    // call PostAsync and wait for it to finish
    Task taskPost =  Task.Run(() => controller.PostAsync(API_FIRM_LINK, aPI_FIRM_LINK));
    taskPost.Wait();
    IHttpActionResult result = taskPost.Result;

    // TODO: compare result with expected result
}
like image 193
Harald Coppoolse Avatar answered Oct 21 '25 15:10

Harald Coppoolse