To Begin with Basic example of Shim, We have 3 Projects and these are on same lines as that of previous blogpost “Basic Stub Sample“.
I’ve not used any System dll in this case so that it is easier to relate between differences in Stub and Shim. Projects are:
- BasicShim : This is simple class library with one method which is to be tested with Fakes Unit Testing
- ToBeShimmed : Contains code for an assembly which is referred in BasicShim Project and will be faked in unit test.
- BasicShimUnitTest: Unit test
Looking into Projects:
Opposed to ToBeStubbed project this project does not contain an y Interface. There is just one Class “FetchRowCount”. This class will ideally contain logic which we need to fake.
Here class FetchRowCount will be used in BasicShim class and method FetchNumberOfRows will be called.
In BasicShim Class we have method “MethodToTest” which we are interested in testing. In case of Shim we are not passing any Interface object to method, so in unit test instead of passing object we will fake the object at runtime.
Similar to previous example, firstly we’ll add reference to all the assemblies we need, Here it will be “BasicShim” for testing and “ToBeShimmed” for Faking.
After that we’ll need to fake assembly TooBeShimmed for that
Goto ToBeShimmed in Unit test project, -> References -> Right Click assembly to be faked. -> Click Add Fakes Assembly
In this sample First thing we’ll have to do is create a ShimContext, this ShimContext is used to fake the assemblies at runtime. Then we’ll set the fake behavior of Method.
If it’s a static method then use <shim class>.<method>, if it is an instance method use <shim class>.AllInstances.<method> to set faking behavior.
Now same as in any Object Oriented Paradigm, create object, call the method and get the return value.
Finally we will assert it with our value i.e. “Average”.
Above is the most basic unit test from fakes which can be done using “shim”.
Keep reading for more posts around this.