For a unit test I want to use the Range attribute from NUnit to test inputs to a function in a range. The lower and upper limits of this range are coded into constant properties of a (Singleton pattern) class. I would like to specify the starting point and end point of the Range attribute with the class properties, something like this:
[Test]
public void sometest([Range(MyClass.LOWER_LIMIT,MyClass.UPPER_LIMIT)] int var)
{
//Do something and assertive with the nice variable
}
However, this approach does not work. Although it is not clear from the documentation itself, it seems that the Range attribute must be provided constant variables. While my class constants are static properties with only get defined, this does capture a constant variable.
I posted and answer to this question, but is this really the way to set the range parameters based on class constant in NUnit? Or is there a more elegant solution?
The following example demonstrates how one can use (constant)properties from a class as values used with the
Rangeattribute from NUnit.The first step is to define constants in your test class, as the
Rangeattribute only works with constants. These constants take the same values as the constants defined in the properties of your class.Second is a Test created to verify that they correspond. If at a later date and time the constants in
MyClasschange, the failure in this test will notify you of this change. Take note that if this test does not pass, any other test using those constants can be regarded as invalid as they rely on false asumptions!Lasty are your actual tests that use those values in the
[Range( start, end)]clause.Alternatively, you can also make use the
[TestFixtureSetUp]attribute instead of the[Test]attribute for theassertConstantsCorrect()method to make all tests in the fixture fail in case theassertConstantsCorrect()fails.Yet another alternative is to make a custom attribute to work for specific methods you as programmer annotate and make those methods fail when
assertConstantsCorrect()fails.