gpt4 book ai didi

c# - 模拟 IList 的单元测试方法

转载 作者:太空狗 更新时间:2023-10-30 01:30:53 24 4
gpt4 key购买 nike

我正在尝试模拟以下方法TryGetApns:

    private readonly Func<string, ICommunicationClient> _communicationFactory;

public CommunicationApiFacade(Func<string, ICommunicationClient> communicationFactory)
{
_communicationFactory = communicationFactory;
}

public IList<ApnResponse> TryGetApns(string tenant)
{
GetApnsResponse response = null;
try
{
var communicationApiClient = _communicationFactory(tenant);
response = communicationApiClient.JctConfigurationService.GetApns();
}
catch (HttpException e)
{
...
}

return response?.Apns ?? new List<ApnResponse>();
}

通过以下测试:

    private Mock<ICommunicationApiFacade> _communicationApiFacade;

[SetUp]
public void SetUp()
{
_fixture = new Fixture()
.Customize(new AutoMoqCustomization());

_communicationApiFacade = _fixture.Freeze<Mock<ICommunicationApiFacade>>();
}

[Test]
public void RunJctTests_WhenJctIsInAPrivateNetwork_ShouldReturnAPassedTest()
{
// Arrange
var jctApn = _fixture.Create<string>();
var message = _fixture.Build<JctLoggedIn>()
.With(x => x.ApnFromDevice, jctApn)
.Create();

var response = _fixture.Build<ApnResponse>()
.With(x => x.IsPrivateApn, true)
.With(x => x.ApnName, jctApn).Create();

_communicationApiFacade.Setup(x => x.TryGetApns(string.Empty))
.Returns(new List<ApnResponse> { response });

var subject = _fixture.Create<NetworkProviderTestRunner>();

// Act
var result = subject.Execute(message);

// Assert
Assert.That(result.Result, Is.True);
}

这是 NetworkProviderTestRunner 类:

    private readonly ICommunicationApiFacade _communicationApi;

public NetworkProviderTestRunner(ICommunicationApiFacade communicationApi)
{
_communicationApi = communicationApi;
}

public JctTest Execute(JctLoggedIn message)
{
var apns = _communicationApi.TryGetApns(message.Tenant);

var jctApn = apns.FirstOrDefault(x => x.ApnName == message.ApnFromDevice);

if (jctApn != null)
{
var privateApn = apns.FirstOrDefault(x => x.PublicApnId.Equals(jctApn.Id));
if (privateApn != null || jctApn.IsPrivateApn)
return new JctTest { Result = true };
}
return new JctTest { Result = false };
}

JctLoggedIn 类:

public class JctLoggedIn : Message
{
public string Imei { get; set; }
public string SimCardIdFromDevice { get; set; }
public string SimCardIdFromStorage { get; set; }
public string ApnFromDevice { get; set; }
public string ApnFromStorage { get; set; }
public string FirmwareFromDevice { get; set; }
public int DeviceTypeFromStorage { get; set; }
public int SerialNumber { get; set; }
}

但出于某种原因,我总是返回一个空列表。我试图在 SetUp 中填充列表并在那里定义输出,但我总是一样。有帮助吗?

最佳答案

虽然您可以在构建 message 对象时显式省略 Tenant 属性,但您也可以将 Mock 设置更改为:

_communicationApiFacade.Setup(x => x.TryGetApns(message.Tenant))
.Returns(new List<ApnResponse> { response });

关于c# - 模拟 IList 的单元测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42512219/

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