When does a mock object enter the replay state?

家住魔仙堡 提交于 2021-01-27 01:40:32

问题


When executing the second line of this code Rhino Mocks throws an InvalidOperationException with a message "This action is invalid when the mock object is in replay state"

var mockScanner = MockRepository.GenerateMock<PortScanner>(null);
        mockScanner.Expect((scanner => { scanner.Scan(null, null); }));

Stepping through the code in a debugger one can see the debugger run the method defined in the class and directly after control leaves this method the exception occurs.

This similar code in another test does work without issue

var mockView = MockRepository.GenerateMock<IScanView>(null);
        mockView.Expect(view => { view.Close(); });
        var controller = new ScanController(mockView);
        controller.Exit();
        mockView.VerifyAllExpectations();

The only difference that I can think of that might be of any consequense between theese two tests is that Exit is a member on an interface while Scan is a virtual member on a class

What am I missing?

Update
Further exploration has indicated that this is related to the way Rhino handles virtual methods. I am focusing mmy study of the documentation here now


回答1:


The exception was caused because Rhino Mocks did not have the required level of access to the type in order to mock it properly. Granting internal access to the Rhino Mocks assembly using InternalsVisibleTo solved the problem.

It's noteworthy that this does not affect interfaces. I believe the reason for this is because the mocking framework needs to override the implementation on a class where there is none on an interface.




回答2:


What happens if you remove the extra set of parentheses from the first expression?

var mockScanner = MockRepository.GenerateMock<PortScanner>(null);
mockScanner.Expect( scanner => { scanner.Scan(null, null); } );


来源:https://stackoverflow.com/questions/932191/when-does-a-mock-object-enter-the-replay-state

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