Alex Rivera | Logout

Mocking objects - declare all methods as virtual or use interface?

Asked 2009-03-27T22:47:13.707
15

In .net, unlike in Java, methods are not virtual by default. In order to use most mock object frameworks, you either have to mark the methods that you want to use on your mock as virtual on the `real' object, or you have to have an interface that you can mock that the class under test will accept in lieu of the implementation.

It seems like bad form to go and mark every method as virtual, but it also seems like bad form to define an interface for every single class.

What is the best thing to do?

Edit
Report

1 Answer

16

If I have to choose between the two, I'd go with the interface thing. An interface is meant to define a contract, which is basically what a mock object is going to adhere to. Marking a method as virtual might have unanticipated side effects. It affects the design of the actual class being mocked. An interface merely defines method names and will have no effect on the real class.

answered 2009-03-27T22:50:45.883

Your Answer