Code Contracts allow for contracts to be defined on interfaces, such as IList<T>
. Some of these, like the a fore mentioned one, have these implemented in .Net already. I'm creating a class that inherits from IList<T>
and I'm writing tests to cover the error conditions such as using the indexer incorrectly (where an ArgumentOutOfRangeException is expected as per the interface specification).
However, I've been unable to create a test to cover this scenario, as a Contract.Requires fails first causing a ContractException. I would like to be able to disable runtime contracts only for this particular test.
Is this possible? I've tried ContractVerificationAttribute(false) on top on my test, but this does not work (I was hoping it would ripple though to all methods called inside it, but this is not the case).
Code Example (Not real production code, but should illustrate what I'm trying to do):
class A : IList<object> {
private IList<object> list = new List<object>();
// All other implementation code
public object this[int index]
{
get { return list[index]; }
// The setter I want to check
set
{
if (index < 0 || index >= Count)
{
throw new ArgumentOutOfRangeException("index");
}
list[index] = value;
}
}
}
[Test]
public void TestSettingAtIndexOutsideListThrowsException(){
try {
A a = new A();
a[0] = new object();
// Some method to fail the test
}
catch(ArgumentOutOfRangeException e)
{
// Check if 'e' is what you expect. If not, fail the test. If it is, pass it.
}
// Some method to fail the test
}