我的代码如下:

SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
var resourceGroup = subscription.GetResourceGroups().FirstOrDefault(rg => rg.Data.Name.Equals(resourceGroupName));

GetResourceGroups()返回ResourceGroupCollection的实例.当ResourceGroupCollectionSingleOrDefault枚举时,我试图让模拟返回ResourceGroupResource的模拟实例.然而,我不确定该怎么做.

到目前为止,我的Moq测试中有以下代码:

this.resourceGroupCollectionMock = new Mock<ResourceGroupCollection>() { CallBase = true };

Mock<ResourceGroupResource> adfResource = new Mock<ResourceGroupResource>();
ResourceGroupData rgData = ResourceManagerModelFactory.ResourceGroupData(resourceIdentifier, resourceGroupName);
adfResource.Setup(x => x.Data).Returns(rgData);

this.subscriptionResourceMock.Setup(x => x.GetResourceGroups()).Returns(this.resourceGroupCollectionMock.Object);

正如您在我的设置中看到的,我模拟GetResourceGroups()以返回模拟ResourceGroupCollection对象.但我不确定如何将adfResource添加到模拟resourceGroupCollectionMock中,以便在枚举后者时返回它.

推荐答案

不幸的是,你不能正确地模拟ResourceGroupData,因为ResourceData‘S Name(1,2)没有定义为virtual/abstract

//Arrange
const string resourceGroupName = "A";

Mock<ResourceGroupData> data = new();
// data
//     .SetupGet(x => x.Name)
//     .Returns(resourceGroupName); 

// The above commented mock setup would throw NotSupportedException

Mock<ResourceGroupResource> resource = new();
resource
    .SetupGet(x => x.Data)
    .Returns(data.Object);

Mock<Response> response = new();
var pagedResource = Page<ResourceGroupResource>.FromValues(new ResourceGroupResource[] { resource.Object }, null, response.Object);
var pagedResources = Pageable<ResourceGroupResource>.FromPages(new Page<ResourceGroupResource>[] { pagedResource });

Mock<ResourceGroupCollection> collection = new();
collection
    .Setup(x => x.GetAll(It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()))
    .Returns(pagedResources);

Mock<SubscriptionResource> subscription = new();    
subscription
    .Setup(x => x.GetResourceGroups())
    .Returns(collection.Object);

//Act
var actual = subscription.Object.GetResourceGroups()
    .FirstOrDefault();
    //.FirstOrDefault(rg => rg.Data.Name.Equals(resourceGroupName)); 

// The above commented line would throw NullReferenceException

//Assert
Assert.NotNull(actual);

因此,如果您不在谓词中使用Name属性(如上面的示例),那么您可以模拟/伪造其余的类.

Csharp相关问答推荐

ß != ss与ICU进行不区分大小写的比较

在实际上是List T的 IESEARCH上多次调用First()是否不好?

如何在Visual Studio中为C# spread操作符设置格式规则?

ListaryImportProperty的默认DllImportSearchPathsProperty行为

MongoDB将JS查询转换为C#的问题

dotnet集合中内部数组的局部变量副本的用途是什么?'

ITypeLib2.GetLibStatistics()在C#中总是抛出AccessViolationException

AsNoTrackingWithIdentitySolutions()似乎不起作用?

将轮询与超时同步

需要在重新启动ApplicartionPool或IIS后启动/唤醒API的帮助

在路由中使用枚举

System.Net.Http.HttpClient.SendAsync(request)在docker容器内的POST方法30秒后停止

调用Task.Run()与DoSomethingAsync()有什么不同?

在swagger示例中添加默认数组列表

HelperText属性不支持复杂内容(混合C#和标记)

在PostgreSQL上使用ExecuteSqlRawAsync的C#11原始字符串文字有区分大小写的问题

实体框架-IsRequired()与OnDelete()

如何对特定异常使用Polly重试机制?

默认架构不存在EF核心迁移

从具有泛型类型约束的类继承-Blazor