You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mock的NetworkInterface中GatewayAddresses计数为0但枚举器有值的问题

问题解决:NSubstitute模拟GatewayAddresses时Count始终为0的问题

问题原因

你仅Mock了GatewayIPAddressInformationCollection的GetEnumerator方法,但未配置它的Count属性。HaveCount断言会直接读取该属性的值,而非通过枚举元素统计数量,因此默认返回0,导致断言失败。

修复后的测试代码

修改Mock GatewayIPAddressInformationCollection的逻辑,添加对Count属性的返回值配置:

<Fact>
Public Sub GetActiveNetworkInterfaces_Should_Return_Correct_Gateway_Address()
  ' Arrange
  Dim oMockGatewayAddresses As GatewayIPAddressInformationCollection
  Dim oGatewayAddresses As GatewayIPAddressInformationCollection
  Dim oMockGatewayInfo As GatewayIPAddressInformation
  Dim oGatewayList As List(Of GatewayIPAddressInformation)
  Dim oEnumerator As IEnumerator(Of GatewayIPAddressInformation)
  Dim oActiveNics As IEnumerable(Of NetworkInterface)
  Dim oNicService As INicService
  Dim oIPAddress As IPAddress
  Dim oMockNic1 As NetworkInterface

  oMockGatewayAddresses = Substitute.For(Of GatewayIPAddressInformationCollection)
  oMockGatewayInfo = Substitute.For(Of GatewayIPAddressInformation)
  oIPAddress = IPAddress.Parse("192.168.1.1")
  oMockNic1 = Substitute.For(Of NetworkInterface)

  ' Mock GatewayIPAddressInformation
  oMockGatewayInfo.Address.Returns(oIPAddress)
  oMockNic1.OperationalStatus.Returns(OperationalStatus.Up)

  ' Mock GatewayIPAddressInformationCollection
  oGatewayList = New List(Of GatewayIPAddressInformation) From {oMockGatewayInfo}
  oEnumerator = oGatewayList.GetEnumerator
  oMockGatewayAddresses.GetEnumerator.Returns(oEnumerator)
  ' 新增:配置Count属性返回列表的实际数量
  oMockGatewayAddresses.Count.Returns(oGatewayList.Count)

  oMockNic1.GetIPProperties.GatewayAddresses.Returns(oMockGatewayAddresses)
  oNicService = Substitute.For(Of INicService)
  oNicService.GetActiveNetworkInterfaces.Returns({oMockNic1})

  ' Act
  oActiveNics = oNicService.GetActiveNetworkInterfaces
  oGatewayAddresses = oActiveNics.First.GetIPProperties.GatewayAddresses

  ' Assert
  oGatewayAddresses.Should.NotBeNull()
  oGatewayAddresses.Should.HaveCount(1) ' 现在会成功
  oGatewayAddresses.First.Address.Should.Be(oIPAddress)
End Sub

补充说明

  • GatewayIPAddressInformationCollection实现了ICollection接口,Count是该接口的核心属性,NSubstitute不会自动根据枚举器内容推导属性值,必须显式配置返回值。
  • 真实环境中GatewayAddresses的Count由系统维护,测试时需手动模拟该值,确保断言与实际行为一致。

内容的提问来源于stack exchange,提问作者InteXX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 22:40:17