Question

If a class does not have an interface, can I use a stub?

I'm trying to stub a method of a class. The class has no interface. The class shows up in Fakes intellisense as a stub. The method is there also but when I try to mock the method, I get the design time error:

Cannot assign to 'MyMethod' because it is a 'method group'

the code

StubClassA classAStub = new StubClassA();
classAStub.MyMethod = (paramA, paramB) => {return 10;};

Is this happening because the class doesn't have an interface? Why is a stub produced if that is the case?

Is my only option to use a shim?

Was it helpful?

Solution

Fakes creates stubs for every unsealed class in the assembly, and stubs every method that can be overridden. Stubs are purely inheritance based, with no magic involved. If MyMethod was able to be stubbed, it would appear as a delegate property named MyMethodParamType1ParamType2.

If you want to override something that normal code cannot override, you require shims. Shims use some kind of obscure magic to modify the IL at runtime and replace methods with delegates. Generally, their use implies a possible weakness in your code, but may be fine with you regardless.

I personally would suggest using an interface if the type really needs to be independent from it's contract, which your problem implies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top