Fedrick
Fedrick

Reputation: 21

How to unit test this function?

I am trying to write unit testing for the following code:

This is my logic

public async Task RemoveUser(string id)
{
    var response = await _graphQLClient.SendMutationAsync<Response>(request);
    if (response.Errors != null)
    {
         throw new ClientException(errorMessages);
    }
}

This is my unit testing

[Test]
public void RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
     _mockGraphQLClient
                .Setup(client => client.SendMutationAsync<object>(It.IsAny<GraphQLRequest>(), It.Is<CancellationToken>(token => token == default)))
                .ReturnsAsync( new GraphQLResponse<object>());

     var psClient = new PsClient(_mockGraphQLClient.Object);
     var removeUserResults = psClient.RemoveUser(id);
     Assert.AreEqual(removeUserResults, /* what to put here? */ );
}

I am confused with what should I compare my results?

And how to handle:

<System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult]

?

Upvotes: 1

Views: 913

Answers (1)

Stefan
Stefan

Reputation: 17658

If you're using async Tasks in your unit test, it's best to make your test function a Task as well.

Luckely the framework supports this.

Adding async will give you the benifit of await as well.

public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
   //...

   await psClient.RemoveUser(id);
   //nothing thrown, all okay --- not really the best test case
}

Normally you would assert some response:

public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
   //...

   var result = await psClient.RemoveUser(id);

   //Assert(result);
}

Or more integration style;

public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
   //...

   var removeResult = await psClient.RemoveUser(id);

   var queryResult = await psClient.GetUser(id);

   //assert user is gone
}

Upvotes: 2

Related Questions