One for the NUnit gurus: Upgrading to 2.x and using new features with existing testing harnesses
I've recently upgraded to NUnit 2.5 (yeah I know) and I was wondering if I could pick someone's brain with this.
I have lots of tests that look like this:
[Test]
public void TestTheSpecialDict() {
int start = 0;
int end = 44;
Dictionary<int, string> = SomeFunction(start, end);
Assert.That(dict1.Count > 0);
// Alright now, some funky values
start = -1;
end = -34;
Dictionary<int, string> dict2 = SomeFunction(start, end);
Assert.T开发者_如何学Pythonhat(dict2.Count == 0);
}
So this specific test ensures that SomeFunction
returns an empty dictionary when the range is invalid, rather than null, for example.
Now I've discovered the [TestCase(...)]
attribute in 2.x. OMG! So I want my test to look like this:
[TestCase(0, 44)]
[TestCase(-1, -34)]
public void TestTheSpecialDict(int start, int end) {
/* ... */
}
Awesome. The problem here of course is that the second Assert fails in the first testcase, and the first assert fails in the second. This is obviously the expected behavior since start
and end
have method scope and apply to both operations. No surprise.
Fixing this isn't a problem:
- Break out the test cases to two different methods. Duplication of code and really, TestCase would be kind of superfluous at this point.
- Add an additional test case parameter (like a sequential value) and conditioning the Assert calls based on that. Lots of work considering the amount of tests I have.
- Something else I haven't though of.
Is there a "cleaner" way? I've looked through NUnit.Framework
and I can't see anything that would let me do this fluently I guess. So I'm wondering if there's someone out there who had this type of "legacy" UT structure with NUnit 1.x and how they migrated up while taking advantage of the new features.
I personally think these TestCase attributes are useful for testing functions that take some parameters and return some value. So in the attributes you can just give it arguments and expected value and it works fine. In your case you could have there either the exact count for your dictionary or a boolean value if its positive. I am not convinced if it would increase the readability in your case though....
Forgive me a bit for not having Visual Studio to test this. but perhaps using Assert.That and passing in an evaluation parameter. Something like this:
[TestCase(0, 44, Is.GreaterThan(0))]
[TestCase(-1, -34, Is.Empty]
public void TestTheSpecialDict(int start, int end, Func<Dictionary<int, string>, bool> condition) {
/* ... */
Assert.That(dict.Count, condition);
}
Again apologize about it not being exact, especially that parameter type might be of is just a guess at it, but the basic idea should hold.
精彩评论