如何在 VB.NET 中使用 RhinoMocks 设置只读属性的返回值? [英] How to setup return value for a readonly property using RhinoMocks in VB.NET?

查看:47
本文介绍了如何在 VB.NET 中使用 RhinoMocks 设置只读属性的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using RhinoMock in VB.NET and I need to set the return value for a readonly list.

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

Here's what I want to do (but doesn't work):

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

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

It fails on the compile because Posts is a readonly property.

然后我尝试了一个 lambda 表达式,它适用于函数调用,但不适用于属性.这无法编译.

Then I tried a lambda expression, which works fine for Function calls, but not so much for Properties. This fails to compile.

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

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

Next (failing) attempt was to use SetupResults, but this failed stating that it cannot be used in Playback mode.

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

这让我回到了我的问题:

Which brings me back to my question:

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

How do I setup a return value for a readonly property using RhinoMocks in VB.NET?

推荐答案

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

Is IUserDto an interface? If it is then it should just work. If it isn't, then the problem could be that the readonly property in question is not overridable. RhinoMocks can only mock properties/methods which are defined in an interface or can be overridden.

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

Here is my (clumsy) attempt at proving that the lambda syntax should work:

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(我没有费心尝试将单元测试框架与此挂钩,但这应该没有区别).

i.e. I would get a message box with the number 10 displayed on it (I didn't bother to try hooking up a unit-testing framework with this but that shouldn't make a difference) when Class1.Test is invoked.

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

Hope that helps (it was an interesting exercise trying to work with RhinoMocks in VB.NET in anycase).

这篇关于如何在 VB.NET 中使用 RhinoMocks 设置只读属性的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆