Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit Test with an array of values

Tags:

I am trying to use NUnit with the values attribute so that I can specify many different inputs without having 100 separate tests.

However now I am realizing there are times where I want to use the same set of inputs but on very different test like below.

Is there a way that I can specify all the values in one place, like an array and use the array for each values attribute?

I want to make sure that the test runs as 100 individual tests, instead of 1 test that runs 100 values.

I have looked in the Nunit documentation, but I cannot find a way to accomplish this. Any ideas?

Code:

[Test] public void Test1([Values("Value1", "Value2", "Value3", ... "Value100")] string value) {     //Run Test here }  [Test] public void Test2([Values("Value1", "Value2", "Value3", ... "Value100")] string value) {     //Run Test here }  [Test] public void Test3([Values("Value1", "Value2", "Value3", ... "Value100")] string value) {     //Run Test here } 
like image 848
Sam Plus Plus Avatar asked Dec 24 '12 18:12

Sam Plus Plus


People also ask

How do I use 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.

How do you write a test case 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.

What is test attribute in NUnit?

The Test attribute is one way of marking a method inside a TestFixture class as a test. It is normally used for simple (non-parameterized) tests but may also be applied to parameterized tests without causing any extra test cases to be generated.


2 Answers

TestCaseSource attribute is suitable here.

See example:

private string[] commonCases = { "Val1", "Val2", "Val3" };  [Test] [TestCaseSource(nameof(commonCases))] public void Test1(string value) {     .... }  [Test] [TestCaseSource(nameof(commonCases))] public void Test12(string value) {     .... } 
like image 89
Alexander Stepaniuk Avatar answered Nov 03 '22 00:11

Alexander Stepaniuk


You can use FactoryAttribute on test method, instead of ValuesAttribute on param. Read more about this here.

Edit: Alexander is right. FactoryAttribute was a temporary part of API. The right path is to use TestCaseSourceAttribute.

like image 21
Pavel Bakshy Avatar answered Nov 03 '22 00:11

Pavel Bakshy