【问题标题】:How can i unit test a method which goes to a static extension method?我如何对静态扩展方法的方法进行单元测试?
【发布时间】:2018-10-23 12:07:48
【问题描述】:

我想要单元测试的方法在某个时候会转到这段代码。

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

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

RequestResourceOwnerPasswordAsync 是库中的静态扩展方法。

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

当我开始测试时,tokenResponse 值为 null,所以我得到一个错误。我尝试了 mock.Setup,但我在扩展方法错误上得到了无效的设置。 我应该怎么做才能使 tokenResponse 具有价值?

【问题讨论】:

  • 你需要分享你的测试代码。

标签: c# unit-testing asp.net-core


【解决方案1】:

你有两个选择

1) 使用垫片。 https://docs.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017

2) 将静态类包装在接口中。

我通常会做第二个,因为我经常发现垫片的维护比包装类的开销更烦人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多