MePengusta
MePengusta

Reputation: 943

How can i unit test a method which goes to a static extension method?

The method which i want to unit test goes to this code at some point.

var resourceOwnerToken = 
      new TokenClient(_tokenClientEndpoint, MobileClient.ClientId, MobileClient.ClientSecret);

IdentityModel.Client.TokenResponse tokenResponse =
      await resourceOwnerToken.RequestResourceOwnerPasswordAsync(model.Phone, model.Password);

RequestResourceOwnerPasswordAsync is a static extension method which is in a library.

public static Task<TokenResponse> RequestResourceOwnerPasswordAsync
    (this TokenClient client, string userName, string password, string scope = null, 
     object extra = null, CancellationToken cancellationToken = default(CancellationToken));

When i start test, tokenResponse value is null so i get an error.I have tried mock.Setup but i got invalid setup on an extension method error. What should i do to make tokenResponse to have a value ?

Upvotes: 1

Views: 1507

Answers (1)

Neil.Work
Neil.Work

Reputation: 1025

You have two choices

1) Use shims. https://learn.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017

2) Wrap the static class in an interface.

I generally do the second one as I often find the maintenance of the shims is more annoying than the overhead of the wrapping class.

Upvotes: 1

Related Questions