开发者

Can Rhino Mock deeper/nested members directly?

开发者 https://www.devze.com 2022-12-18 17:23 出处:网络
Is it possible to mock a stub/mock\'s object member call without having to define that as a stub, and also set the return value as all seperate verbose lines?

Is it possible to mock a stub/mock's object member call without having to define that as a stub, and also set the return value as all seperate verbose lines?

Example:

    [TestMethod]
    public void AssignedPermissions_AssociateExists_ReturnsEdit_Rhino()
    {

       //Arrange
        var fakeConfiguration = MockRepository.GenerateStub<IDomainControllerConfiguration>();
         var fakeAssociateRepository = MockRepository.GenerateStub<IAssociateRepository>();
        fakeCo开发者_Python百科nfiguration.Stub(x => x.AssociateRepository).Return(fakeAssociateRepository);
        fakeAssociateRepository.Stub(x=>x.GetAssociatesByRole(null,false,null)).IgnoreArguments()
            .Return(new IAssociate[]{MockRepository.GenerateStub<IAssociate>()});

        var domain = new DomainController(fakeConfiguration);

        const AssignedPermission expected = AssignedPermission.Edit;

        //Act
        AssignedPermission actual = domain.AssignedPermissions();

        //Assert
        Assert.AreEqual(expected, actual);
    }

Are all those temporary variables necessary just to stub out nested method calls?


I've never used the functionality, so I'm not 100% certain that this will work, but theoretically Rhino mocks supports "recursive mocking", which should allow you to at least cut out the fakeAssociateRepository by doing something like this:

var fakeConfiguration = MockRepository.GenerateStub<IDomainControllerConfiguration>();
fakeConfiguration.Stub(x => x.AssociateRepository.GetAssociatesByRole(null,false,null))
            .IgnoreArguments()
            .Return(new IAssociate[]{MockRepository.GenerateStub<IAssociate>()});

var domain = new DomainController(fakeConfiguration);

(note: code not tested, or even compiled)


Just wanted to share my input on this, since I just spent the last few hours wrestling with it. The answer posted above by Alconja absolutely works, but if you plan to use it for "AssertWasCalled" type of assertion, it does not assert the way I expected it to. It seems that the AssertWasCalled methods tried to assert the "get accessor" associated with the "nested" object.

For instance, if you wanted to do this:

fakeconfiguration.AssertWasCalled(x => x.AssociateRepository.GetAssociatesByRole(null, false, null));

You would get an exception such as

System.InvalidOperationException : Previous method 'IDomainControllerConfiguration.get_AssociateRepository();' requires a return value or an exception to throw.

Because the AssertWasCalled is asserting the get-accessor of the AssociateRepository property, rather than the GetAssociatesByRole() method. In the end, for my case I had to use the OP's methodology of creating mutliple stubs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号