Can anyone tell me very clearly what's the main difference between a shim
and a stub
during unit testing?
I know about mock objects and I read about shims and stubs but it's still not clear in which context I should use a shim or a stub.
Shims divert calls to specific methods to code that you write as part of your test. Many methods return different results dependent on external conditions, but a shim is under the control of your test and can return consistent results at every call. This makes it easier to write the tests.
What Does Shim Mean? Shim, in C#, is a template class that is derived from a base class with derived classes that inherit the data and behavior of the base class and vary only in the type. The derived class of the shim class reuses the implementation provided by the shim class.
Unit testing allows software developers to actually think through the design of the software and what has to be done before they write the code. This can help them to stay focused and can also help them to create much better designs.
Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. This testing methodology is done during the development process by the software developers and sometimes QA staff.
Let me cite Martin Fowler's article Mocks Aren't Stubs:
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
Mocks are [...] objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
So mocks can directly make a test fail if an expectation is violated. Stubs don't do that.
Shims (or Moles) differ from both of them in that they can be used to replace hard-coded dependencies like static methods. You should avoid that IMO and prefer a refactoring, which makes these dependencies replaceable. See this thread for further discussion, especially Jim Cooper's answer.
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