Using NUnit I want to test whether given string is shorter than 200 characters. My goal is not to hard-code this string, because I will have a string with 201 characters as counter-part in another test.
Lets look at the test signature:
[TestCase("GetTooLongName")]
public void If_NameIsTooLong_ReturnError(string name)
I have tried to use a string constructor that takes 2 params, a char and number of times it will be concatenated. I tried to get it from field and from function:
private static readonly string GetTooLongName = new('x', 201);
private static string LongNameStillOk => new('x', 200);
In the end I get an error:
An attribute must be a constant expression...
Is there a nice and clean way to provide such long string to test attribute?
CodePudding user response:
Finally I have used TestCaseSource attribute of NUnit.
The code appears as follows:
private const int MAX_ALLOWED_STRING_LENGTH = 200;
private static string[] _nameTooLongSource= {new('x', MAX_ALLOWED_STRING_LENGTH 1)};
[TestCaseSource(nameof(_nameTooLongSource))]
public void If_NameIsTooLong_ReturnError(string name)
This then creates a scenario for each of the elements of _nameTooLongSource array. It has only one element which is the long string.
