【问题标题】:How to setup return value for a readonly property using RhinoMocks in VB.NET?如何在 VB.NET 中使用 RhinoMocks 设置只读属性的返回值?
【发布时间】:2009-07-06 15:29:13
【问题描述】:

我在 VB.NET 中使用 RhinoMock,我需要为只读列表设置返回值。

这是我想要做的(但不起作用):

dim s = Rhino.Mocks.MockRepository.GenerateStub(of IUserDto)()
s.Id = guid.NewGuid
s.Name = "Stubbed name"
s.Posts = new List(of IPost)

编译失败,因为 Posts 是只读属性。

然后我尝试了一个 lambda 表达式,它适用于函数调用,但不适用于属性。编译失败。

s.Stub(Function(x As IUserDto) x.Posts).Return(New List(Of IPost))

下一次(失败)尝试是使用 SetupResults,但失败表明它不能在播放模式下使用。

Rhino.Mocks.SetupResult.For(s.Posts).Return(New List(Of IPost))

这让我回到我的问题:

如何在 VB.NET 中使用 RhinoMocks 为只读属性设置返回值?

【问题讨论】:

  • 为什么 Rhino.Mocks.SetupResult.For(s.Posts).Return(New List(Of IPost)) 失败了?
  • 在播放模式下无效,失败
  • 您能提供更多代码吗?听起来您可能会将新的 AAA 语法与旧的 Record-Playback 方法混为一谈,这无济于事。我不熟悉 VB.NET,但是在 C# 中可以很容易地对只读属性(即没有设置器的属性)进行存根。
  • 顺便问一下,您的 lambda 表达式尝试是如何失败的?是测试失败还是代码编译失败?
  • 是的,我正在混合 AAA 和录制/播放。我正在抓住任何可用的吸管。我不熟悉使用模拟和 AAA 风格“更适合”我,但我会做任何有效的事情。 lambda (s.Stub(Function....) 编译失败。

标签: vb.net rhino-mocks


【解决方案1】:

IUserDto 是接口吗?如果是,那么它应该可以工作。如果不是,那么问题可能是所讨论的只读属性不可覆盖。 RhinoMocks 只能模拟在接口中定义或可以被覆盖的属性/方法。

这是我(笨拙的)尝试证明 lambda 语法应该有效:

Imports Rhino.Mocks

Public Class Class1

    Public Sub Test()
        Dim s = MockRepository.GenerateMock(Of IClass)()
        Dim newList As New List(Of Integer)

        newList.Add(10)

        s.Stub(Function(x As IClass) x.Field).Return(newList)

        MsgBox(s.Field(0))

    End Sub

End Class

Public Class AnotherClass
    Implements IClass

    Public ReadOnly Property Field() As List(Of Integer) Implements IClass.Field
        Get
            Return New List(Of Integer)
        End Get
    End Property
End Class

Public Interface IClass
    ReadOnly Property Field() As List(Of Integer)
End Interface

即当调用 Class1.Test 时,我会得到一个显示数字 10 的消息框(我没有费心尝试用它连接一个单元测试框架,但这不应该有什么不同)。

希望有所帮助(无论如何,尝试在 VB.NET 中使用 RhinoMocks 是一个有趣的练习)。

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多