Unit Test Logic

I have a unit test like this:

[Test] public void DataIn_NoOfRowsReached_CreatesSequentialData() { //Assert MyLogic logic = SetupLogic(); logic.NoOfRows = 3; logic.DataIn(1, "1,4,7"); logic.DataIn(2, "2,5,8"); logic.DataIn(3, "3,6,9"); CollectionAssert.AreEqual(new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9" }, logic.ExpectedValues); } 

Each call to DataIn adds the transferred data to a separate list depending on the identifier (1st parameter). When the NoOfRows number is equal to the input DataIn identifier, it combines the data that should be sequential. Then I check it out.

Now I want to use test cases, but I see no easy way to do this without using operators and various optional parameters in the test method. I really don't want to duplicate tests for different scenarios.

The maximum of NoOfRows is 6.

+4
source share
3 answers

I believe that this is what you are looking for. Use the params keyword to allow passing an arbitrary number of lines.

 [Test] public void DataIn_NoOfRowsReached_CreatesSequentialData() { MyGenericTest("1,4,7", "2,5,8", "3,6,9"); } private void MyGenericTest(params string[] inputs) { //Assert MyLogic logic = SetupLogic(); logic.NoOfRows = inputs.Length; List<string> allNumbers = new List<string>(); for(int i = 0; i < inputs.Length; i++) { logic.DataIn(i + 1, inputs[i]); allNumbers.AddRange(inputs[i].Split(','); } allNumbers.Sort(); CollectionAssert.AreEqual(allNumbers.Distinct(), logic.ExpectedValues); } 

This is just sorting strings ... if you have numbers that are greater than 9, you want to add your own comparison function to Sort () .

+2
source

If you use NUnit and want to run several test cases with different inputs, you can use the Values ​​attribute, http://nunit.com/index.php?p=values&r=2.6 .

Your unit test might look like this:

 [Test] public void DataIn_NoOfRowsReached_CreatesSequentialData([Values(new[] { "1,4,7", "2,5,8", "3,6,9" }, ...)] string[] vals) { //Assert MyLogic logic = SetupLogic(); logic.NoOfRows = vals.Length; for (var i = 0; i < vals.Length; ++i) logic.DataIn(i + 1, vals[i]); CollectionAssert.AreEqual(new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9" }, logic.ExpectedValues); } 
+1
source

If you want to write some smart tests, you can probably create the expected array with the numbers you entered as input and sort them, you can track the numbers you enter as part of each line (use some numbers to create the line) . Other than that, I do not see too many improvements.

0
source

Source: https://habr.com/ru/post/1402444/


All Articles