To this point I've been using standard [Test] attributes and since seeing this attribute in the documentation I've been thinking about uses for it. Now that I've started using [TestCase] I've thought of some other uses for it cutting my test fixtures down to 1/2 or less the size previously.
Below is an simple example of the code without the [TestCase] using the traditional [Test] attribute:
The above code can be trimmed down to one function using the [TestCase] attribute:
The other beautiful thing about [TestCase]s is that it collapses each test case underneath a node which actually looks cleaner:
A couple of notes on the code above. The compiler (C# here) will not allow you to use object initializers as a parameter to the [TestCase] so you cannot create a test function Validate(object myUser) and do something like below.
This is because the compiler will only allow constants in attributes, however if you really need something like this, NUnit allows a work around. This is documented here.
2 comments:
hey,
you forgot to link the "documented here" sentence at the bottom when talking about the object initializer workaround, which is exactly what I was looking for. doh!
great blog btw.
ta,
Matt
I don't think there's a decent workaround.
The only way is to pass constants in parameters: if your User class has FirstName and LastName properties, you can do
[TestCase("foo", "bar")]
void TestMe(string firstName, string lastName) {
var user = new User(firstName, lastName);
...
}
Post a Comment