如何模拟没有setter的属性?

时间:2011-12-11 02:55:13

标签: c# unit-testing rhino-mocks

我正在尝试模拟界面。我想设置“MockThisProperty”的属性没有setter。我无法更改接口源。我得到的错误是

上一个方法'IThirdPartyInterface.get_MockThisProperty();'需要返回值或抛出异常。

我尝试过DynamicMock,Strictmock,部分模拟等等。

当我尝试SetupResult.For(thirdParty.MockThisProperty = mockedValue)时将无法编译,因为没有setter。

使用mstest的最新Rhino模拟

亏本,这是代码......

        var stuff = _Mockery.Stub<Hashtable>();
        matchItem.Add(key, "Test"); 

        var thirdParty = _Mockery.Stub<IThirdPartyInterface>();
        SetupResult.For(thirdParty.MockThisProperty).Return(stuff);

        _Mockery.BackToRecordAll();


       //more code

        _Mockery.ReplayAll();

        Assert.IsTrue(MethodToTest(thirdParty));

        _Mockery.VerifyAll();

2 个答案:

答案 0 :(得分:7)

这对我有用:

var thirdParty = Rhino.Mocks.MockRepository.GenerateStub<IThirdPartyInterface>();
thirdParty.Stub(x => x.MockThisProperty).Return("bar");
string mockPropertyValue = thirdParty.MockThisProperty; //returns "bar"

答案 1 :(得分:0)

我在尝试模拟在没有 setter 的接口中定义的属性时偶然发现了这篇文章。

由于我还没有使用 Rhino 并且不想要除 Moq 之外的其他依赖项,我发现

mockedWithMoq.SetupGet(x => x.PropertyWithGetterOnly).Returns("foo")

也会做这项工作。

相关问题