What should I consider when choosing a mocking framework for .Net

后端 未结 8 1980
梦如初夏
梦如初夏 2020-12-12 18:20

There are lots of mocking frameworks out there for .Net. There is no clear winner that has superseded the others in every way. The leading mocking frameworks also have many

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 18:44

    So what questions should I by asking about the project and myself to help decide on the best mocking framework to use in a given case?

    The questions you should be asking about the project is: Has the project been developed with the SOLID principles, or not? Is this a project that has loose coupling and high cohesion? Have good OO principles been utilized in building the project? Is a Dependency Injection container being utilized? Has the system been coded in a Design by Contract method (utilizing Interfaces thoroughly)?

    If you answer yes to these questions, then you can utilize a mocking framework like RhinoMocks, which is what some would call an "opinionated" framework. RhinoMocks, and some other mocking frameworks, have very strong opinions about how a system should be designed in order for objects to be mocked. A framework like RhinoMocks expects your project to be designed a certain way. Mocking is certainly a lot easier with RhinoMocks when you've built your code the right way (no sealed classes, no statics, heavy use of interfaces, virtual on class methods, etc.)

    If you answer no to those questions, or if you're working on a legacy system with a lot of highly coupled classes, then your only choice is going to be TypeMock, which can mock just about anything.

    It would also be useful to know why you choose the mocking framework you are currently using and if you are still happy with that choose.

    I chose RhinoMocks because at the time (3+ years ago) it was clearly the most mature mocking framework with the most features. I've stayed with it because it has evolved in away that makes my life much easier (the advent of the AutoMocking container being a gigantic step toward efficiency).

    What I like about RhinoMocks, other than the feature set and ease of use, is that it guides me toward a better design in my code. I am not a perfect programmer, and I am going to make mistakes in design. But tools like RhinoMocks and NHibernate help guide me toward a better design, because when I do make mistakes and create poor design, these tools become painful to work with. NHibernate, for instance, is painful to work with if you have a bad database design. RhinoMocks is very painful to work with if you have a poor class design, aren't using interfaces, aren't using IoC... etc.

    I like RhinoMocks because it ultimately helps me be a better developer, and not just because I'm testing my code, but because I'm shaping my code - designing it - in a better manner.

提交回复
热议问题