Skip to content


Add support for code contracts #94

apeel opened this Issue · 4 comments

3 participants


At the moment, Moq offers no support for Code Contracts, which is included in C# 4.0.

While we can disable code contracts on test assemblies, contracts often provide very useful information about the external facing requirements of our libraries, so this is a less-than-ideal solution.

The workaround to this is to include intermediary assumptions about the library. This is highly verbose, and completely clutters up any tests using code contracts.

Entity mock = Mock.Of<Entity>();
Contract.Assume(mock != null);

For anything that requires a non-null object by contract, we would need to explicitly specify an assumption about the output of the Moq library. This requires a huge amount of extra intermediary code, at least one assumption for every mock.

The best alternative is to include code contract information in the Moq library itself, which would provide clear guarantees as to the preconditions and postconditions of the Moq API.

It's worth noting that this is likely worth doing in and of itself as code contracts can add a great degree of robustness to an existing library.


See this pull request for a quick implementation that adds basic compatibility with Code Contracts.

@apeel apeel closed this
@apeel apeel reopened this

Does this build on SL or do we have conditionals in place?


Code Contracts should be fully support on the Silverlight platform. It compiles.

kzu commented

This doesn't compile or work on v3.5.

I'm reverting this change until that's figured out.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.