[英]Is it possible/supported in AutoFixture with NSubstitute to return automatic values from proxy interfaces
[英]Return multiple list values from method NSubstitute
我在文檔中讀到,您可以使用 Configure() 以便在每次調用方法時返回不同的值。 但是,我使用的是 NSubstitute 4.2.1,並且無法訪問 API 上的“Configure()”。 我想知道是否有任何解決方法可以返回不同的值。
到目前為止,我已經嘗試過以下內容:
var output = new List<List<MobileGetDocumentAuthorizationDto>>();
var counter = 0;
apiLayer.GetByIds(idStack).ReturnsForAnyArgs(x =>
{return output[counter++];
});
我在循環中向 output 添加新值。
每次調用 apiLayer.GetByIds() 時,我都想返回不同的列表。
感謝您分享這方面的專業知識。
這可以通過多種不同的方式完成,但以下是使用以下類型的簡單示例
public interface IService {
List<MyDto> GetByIds(int[] ids);
}
public class MyDto {
public int Id { get; set; }
}
示例測試顯示如何使用Returns
function 生成隨機結果。
[TestClass]
public class NSubTests {
[TestMethod]
public void Should_Return_Multiple_ListValues() {
//Arrange
IService apiLayer = NSubstitute.Substitute.For<IService>();
Random randomIds = new Random(9999);
Random randomCount = new Random();
apiLayer.GetByIds(Arg.Any<int[]>()).Returns(args => {
var ids = args.ArgAt<int[]>(0);
var count = randomCount.Next(ids.Length);
var items = Enumerable.Range(0, count)
.Select(_ => new MyDto { Id = randomIds.Next() })
.ToList();
return items;
});
//Act
var list1 = apiLayer.GetByIds(new[] { 1, 2, 3, 4, 5 });
var list2 = apiLayer.GetByIds(new[] { 1, 2, 3, 4, 5 });
//Assert - FluentAssertions
list1.Should().NotBeSameAs(list2);
}
}
每次調用模擬成員時,它都會返回一個根據作為輸入傳遞的 id 數量生成的不同列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.