user3301081
user3301081

Reputation:

RhinoMocks Expect not working as 'expected'

I have the following test code

//setup the mock
SomeResource mock = MockRepository.GenerateMock<SomeResource>();
mock.Stub(m => m.GetNumOfResources()).Return(1);
mock.Stub(m => m.SomeProp).Return(SomeEnum.YO);
mock.Expect(m => m.SomeProp).Repeat.Once();
mock.Replay();

//execute
SomeClass sc = new SomeClass();
sc.SetSomeResource(mock);
sc.MethodToTest();

//verify
mock.VerifyAllExpectations();

I want to verify that SomeProp was accessed. Whenever I debug through the code I can see that SomeProp is being accessed, and yet the expectation I set up above is throwing an exception in the test, saying it wasn't. I'm new to Rhino Mocks so I've clearly not set something up correctly but I cannot see what. Any ideas?

Edit: Here's basically the code/logic I am testing:

private bool MethodToTest()
{
    bool ret= false;

    if (resource == null)
    {
        try
        {
            resource = new SomeResource();
        }
        catch (Exception e)
        {
            //log some error
        }
    }

    if (resource != null && resource.GetNumResources() > 0)
    {
        bool ok = true;

        try
        {
            resource.SetSomething("blah");
        }
        catch (Exception)
        {
            ok = false;

            // Test that SomeProp was accessed here
            SomeEnum val = resource.SomeProp;
        }

        ret = ok;
    }


    return ret;
}

Upvotes: 0

Views: 806

Answers (1)

Nkosi
Nkosi

Reputation: 247018

A bit of API confusion between mocks and stubs as they relate to Rhino Mocks API and interaction based testing

//Arrange
SomeObj mock = MockRepository.GenerateMock<SomeObj>();
mock.Expect(_ => _.GetNumOfThings()).Return(1);
mock.Expect(_ => _.SetSomething(Arg<string>.Any())).Throw(new Exception());
mock.Expect(_ => _.SomeProp).Return(SomeEnum.YO).Repeat.Once();
SomeClass sc = new SomeClass();
sc.SetSomeResource(mock);

//Act
sc.MethodToTest();

//Assert
mock.VerifyAllExpectations();

Reference Rhino Mocks - Stub .Expect vs .AssertWasCalled

Upvotes: 1

Related Questions