我試圖嘲弄以下方法TryGetApns:單元測試方法嘲弄的IList
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 };
}
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; }
}
但由於某種原因,我總是回到一個空列表:0 JctLoggedIn類。我試着填充SetUp中的列表,並在那裏定義輸出,但我總是一樣的。任何幫助?
您可以發佈NetworkProviderTestRunner的代碼?根據您的設置,TryGetApns將只返回您在租戶爲空字符串時設置的值。值得檢查一下你是否按照設置通過了正確的值。 – Mani
完成了@Mani – Rober
請同時發佈'JctLoggedIn',以便我們看看'Tenant'是否可寫。另一方面,你可以刪除第一塊代碼,因爲你用一個測試double來代替所有的代碼。 –