gpt4 book ai didi

c# - 模拟 Azure MobileServiceClient

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:14 25 4
gpt4 key购买 nike

我有一个方法需要进行单元测试,但我被其中的模拟部分困住了。

private async void LoginCommandAsync()
{

.....

CancellationToken ct;
var result = await ClientAuthorizationService.CurrentClient.InvokeApiAsync(Constants.ApiConstants.AzureAuthMeData,
null, HttpMethod.Get, null, ct);

....
}

我尝试使用 Moq 模拟 Microsoft.WindowsAzure.MobileServices.MobileServiceClient。不幸的是,我总是在最后一行代码中得到 System.InvalidCastException

        var currentClient = new Mock<IMobileServiceClient>(MockBehavior.Loose);

currentClient.Setup(x => x.InvokeApiAsync(Constants.ApiConstants.AzureAuthMeData,
null, HttpMethod.Get, null, ct)).Returns(Task.FromResult(token));

var disposableCurrentClient = currentClient.As<IDisposable>();

ClientAuthorizationService.CurrentClient = (MobileServiceClient)disposableCurrentClient.Object;

MobileServiceClient 继承自 IMobileServiceClient,IDisposable 但无论我如何尝试使用/分配模拟对象......它都不起作用。

public class ClientAuthorizationService : IClientAuthorizationService
{
public MobileServiceClient CurrentClient { get; set; }
public ClientAuthorizationService()
{
CurrentClient = new MobileServiceClient(Constants.ApiConstants.ApplicationUrl);
}
}

最佳答案

ClientAuthorizationService.CurrentClient 成员/属性从 MobileServiceClient 更改为 IMobileServiceClient

public interface IClientAuthorizationService  {
IMobileServiceClient CurrentClient { get; set; }
}

public class ClientAuthorizationService : IClientAuthorizationService {

public ClientAuthorizationService() {
CurrentClient = new MobileServiceClient(Constants.ApiConstants.ApplicationUrl);
}

public IMobileServiceClient CurrentClient { get; set; }
}

这将允许在测试时分配客户端的模拟,因为 ClientAuthorizationService 现在依赖于抽象而不是实现问题。

//....

var clientAuthorizationService = new Mock<IClientAuthorizationService>();

var currentClient = new Mock<IMobileServiceClient>();

currentClient
.Setup(_ => _.InvokeApiAsync(It.IsAny<string>(), null, HttpMethod.Get, null, It.IsAny<CancellationToken>()))
.ReturnsAsync(token);

clientAuthorizationService
.Setup(_ => _.CurrentClient)
.Returns(currentClient.Object);

//.....

此外,建议不要使用 async void 除了事件处理程序

因此需要对被测代码进行相应的更新。

private async Task LoginCommandAsync() {

//.....

CancellationToken ct;
var result = await ClientAuthorizationService.CurrentClient.InvokeApiAsync(Constants.ApiConstants.AzureAuthMeData,
null, HttpMethod.Get, null, ct);

//....
}

关于c# - 模拟 Azure MobileServiceClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53251995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com