Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit TestCaseSource

Tags:

I'm having a go with the TestCaseSource attribute. One problem: when the sourceName string is invalid, the test just gets ignored instead of failing. This would be really bad if the source method gets renamed, the sourceName string doesn't get updated, and then you lose the coverage that the test provided. Is there a way to change the behaviour of NUnit, so that the test fails if the sourceName is invalid?

like image 369
DanB Avatar asked Jul 30 '12 13:07

DanB


People also ask

What is Testcasesource in NUnit?

TestCaseSourceAttribute is used on a parameterized test method to identify the source from which the required arguments will be provided. The attribute additionally identifies the method as a test method. The data is kept separate from the test itself and may be used by multiple test methods.

Does NUnit have data provider?

All of the built-in attributes allow for data to be provided programmatically, but NUnit does not have any attributes that fetch the data from a file or other external source.

How do you write a TestCase in NUnit?

There are other NUnit attributes that enable you to write a suite of similar tests. A [TestCase] attribute is used to create a suite of tests that execute the same code but have different input arguments. You can use the [TestCase] attribute to specify values for those inputs.

How do I run multiple test cases in NUnit?

If you add a second parameter with the Values attribute, for per value of the first parameter, NUnit will add a test for every value of the second parameter. Another way to avoid having to write duplicate tests when testing the same behaviour with different inputs is to use TestCase attribute on the test itself.


1 Answers

This is resolved in NUnit 2.6.2. There is a new constructor for the attribute that takes a Type (which must implement IEnumerable); it "is recommended for use in preference to other forms because it doesn't use a string to specify the data source and is therefore more easily refactored." (From the documentation.)

This does require that your test runner supports the latest NUnit.

A very basic example (see the above documentation link for more details):

public class TestDataProvider : IEnumerable {     public IEnumerator GetEnumerator()     {         return new List<int>{ 2, 4, 6 }.GetEnumerator();     } }  [TestFixture] public class MyTests {     [TestCaseSource(typeof(TestDataProvider))]     public void TestOne(int number)     {         Assert.That(number % 2, Is.EqualTo(0));     } } 
like image 120
TrueWill Avatar answered Sep 27 '22 01:09

TrueWill