How do you assert a generic method was called with Rhino Mocks?

三世轮回 提交于 2019-12-11 16:12:46

问题


I have the following test to verify that my repository is calling it's respective session (I've rewritten it to highlight the actual problem):

[Test]
    public void Why_Does_This_Fail()
    {
        var objectUnderTest = new SomeGenericsProblem();

        var fakeSession = MockRepository.GenerateMock<ISession>();
        fakeSession.Expect(s => s.Query<SomeClass>());

        objectUnderTest.NotWorking<SomeClass>();

        fakeSession.AssertWasCalled(t => t.Query<SomeClass>());
    }

but when I run the test I get this:

System.InvalidOperationException : Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).(C#) / Overridable (VB) method).

Any ideas what I'm doing wrong here? The session that I'm mocking is an interface, so it has to be virtual/overridable.

I have a feeling it has something to do with the fact that my Query method is a generic, but I don't know any other way to express what I'm trying to test.

Also, If I remove the part that sets up the expectation (i.e. this line of code:)

fakeSession.Expect(s => s.Query<SomeClass>());

I get a different exception which is equally confusing to me:

System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method calloverridable (VB.Net) method call


回答1:


So I figured out what was wrong.

ISession comes from NHibernate, which I probably should have mentioned.

The reason why this is cruicialy important is because

session.Query<T> 

(which is what I'm trying to mock), is an EXTENSION METHOD.

Rhino Mocks apparently does not have the capability of mocking extension methods, hence why it's giving me the weird error.

So hopefully I'll have saves someone else the time and agony I've gone through in trying to figure out why my test won't pass.

The only solution that I've read about for this is to actually change the design of the extension method (which I can't do because it's part of NHibernate), or to use a different mocking framework like TypeMock.




回答2:


[Test]
public void Query_WhenCalled_CallsSessionQuery()
{
        // arrange
        var session = MockRepository.GenerateStub<ISession>();

        var r = new Repository(session);

        // act
        r.Query<SomeClass>();

        // assert
        session.AssertWasCalled(s => s.Query<SomeClass>());
}


来源:https://stackoverflow.com/questions/3678487/how-do-you-assert-a-generic-method-was-called-with-rhino-mocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!