How to write Internal mockable method
We are using Moq as our mocking framework, the problem is that type that needs to be mock-able is done using an interface, the problem with that is anything in that interface will be public and therefore considered par开发者_JS百科t our public API.
is there a way to have to have a member that is mockable and not public?
If I've understood you correctly you want to be able to apply an interface to a type to support mocking, but do so in a manner that the interface will not be visible to public consumers of you code.
Well, one option is that you could implement an internal
interface and use the [assembly:InternalsVisibleToAttribute]
to make the internal types accessible to your unit tests.
[assembly:InternalsVisibleTo("MyUnitTestAssembly")]
internal interface ISomeInterfaceForMocking { ... }
public class MyMockableType : ISomeInterfaceForMocking { ... }
Is http://code.google.com/p/moq/wiki/QuickStart#miscellaneous (see the Miscellaneous part) any use (i.e., the syntax for mocking protected
stuff)?
The ISP says there shouldnt be magic stuff on an interface that only some people are interested in. Also, have you considered sticking in a single virtual
method rather than a whole interface and/or a base interface for the mockable bit? Or just have a specific interface for it. Remember, if it's hard to mock or test, there's generally something that can be improved in your code (as opposed to finding technical tricks for jumping hoops and/or going to overly powerful mocking frameworks).
Also, I bet if you post a slimmed down version of your test, someone will be able to refactor it just right and we'll all learn something.
精彩评论