I'm new to mocking, I have a new .net web project that is in UI->BLL->DAL->DB structure, I use NUnit to do some testing currently. I intent to use it to test middle tier so I don't have to actually write to DB.
Now, I've never done any mocking, don't quite know where to start, so I am looking for a mocking framework that has some end to end samples! Could someone point to me a some mocking material that starts from the beginning and with full samples please?
Thank you,
Ray.
gMock is a library (sometimes we also call it a “framework” to make it sound cool) for creating mock classes and using them. It does to C++ what jMock/EasyMock does to Java (well, more or less).
Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
Mocking Private or Protected Methods You must always put a mock method definition ( MOCK_METHOD ) in a public: section of the mock class, regardless of the method being mocked being public , protected , or private in the base class.
In gMock we use the EXPECT_CALL() macro to set an expectation on a mock method. The general syntax is: EXPECT_CALL(mock_object, method(matchers)) . Times(cardinality) .
You should check out some videos about mocking on Dimecasts.net, it's a quick way to get a feel over what mocking is about and get started on your own code.
Introduction to Moq
Introduction to RhinoMocks
At the moment there are a number of different mocking frameworks. I would recommend that you either take a look at RhinoMock or TypeMock. Both are free for personal / open source projects. TypeMock has a corporate license as well.
RhinoMock forces you to refactor your code for testability (if needed, if you already have testable code you're doing good). This requires more work, but it will leave you with code which is loosely coupled which is a boon in itself. Due to this there are certain constructs you simply can't mock directly with Rhino. However, you can always introduce additional layers of indirection and solve it that way. The bottomline however is this: you need to do some more work, but ultimately the refactoring will benefit your code.
TypeMock on the other hand works by modifying the code on-the-fly (it uses the profiler API to inject code). This allows you to employ mocking for code that isn't otherwise suitable for this type of testing. TypeMock will pretty much allow you to mock anything (except for mscorlib), so it is easy to get started and it works well with legacy code. However, because you're not forced to refactor your code, you don't get the additional benefit of loosely coupled types. Additionally TypeMock will sometimes lead to very weird errors due to the fact that the running code is modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With