Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put new List<int> {1} in an NUNIT TestCase?

I have the method:

public static int Add(List<int> numbers)     {         if (numbers == null || numbers.Count == 0)             return 0;          if (numbers.Count == 1)             return numbers[0];           throw new NotImplementedException();     } 

Here is my test against it, but it does not like new List<int> {1} in the TestCase:

    [TestCase(new List<int>{1}, 1)]     public void Add_WithOneNumber_ReturnsNumber(List<int> numbers)     {          var result = CalculatorLibrary.CalculatorFunctions.Add(numbers);          Assert.AreEqual(1, result);     } 

It gives me the error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Do I have to do it like this:

    [Test]     public void Add_WithOneNumber_ReturnsNumber()     {          var result = CalculatorLibrary.CalculatorFunctions.Add(new List<int>{7});           Assert.AreEqual(7, result);          var result2 = CalculatorLibrary.CalculatorFunctions.Add(new List<int> {3});          Assert.AreEqual(4,result2);     } 
like image 607
xaisoft Avatar asked Oct 20 '13 16:10

xaisoft


People also ask

Which attribute in NUnit lets you execute a method before and after a TestCase?

This attribute is to identify methods that are called once prior to executing any of the tests in a fixture.

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.


2 Answers

There is one option to use TestCaseSource attribute. Here I provide a non-assert test with two cases just to see how it works:

[TestFixture] public class TestClass {     private static readonly object[] _sourceLists =      {         new object[] {new List<int> {1}},   //case 1         new object[] {new List<int> {1, 2}} //case 2     };      [TestCaseSource("_sourceLists")]     public void Test(List<int> list)     {         foreach (var item in list)             Console.WriteLine(item);     } } 

Anyhow I have to mention it is not the most evident solution and I would prefer neatly organized fixtures ignoring the fact they are more verbose

More information: https://github.com/nunit/docs/wiki/TestCaseSource-Attribute

like image 95
Yurii Hohan Avatar answered Sep 18 '22 02:09

Yurii Hohan


My solution is simpler, I just use params. I hope this works for you!

[TestCase(1, 1)] [TestCase(10, 5, 1, 4)] [TestCase(25, 3, 5, 5, 12)] public void Linq_Add_ShouldSumAllTheNumbers(int expected, params int[] numbers) {     var result = CalculatorLibrary.CalculatorFunctions.Add(numbers);     Assert.AreEqual(expected, result); } 
like image 25
Jaider Avatar answered Sep 21 '22 02:09

Jaider