Parameterized Test Example in .NET Core Using NUnit.

A lot of times when writing unit tests we end up with a lot of test methods that look the same and actually do the same thing. Also, there are special cases where we want to have high test coverage and in-depth test access for our crucial and very important core functionality methods.

For example, when creating a framework or a library, usually we want to write many tests and cover all possible aspects and outcomes, which may lead to a large amount of certain behavior test methods.

Very often, we end up with these test methods with the same logic and behavior but with different input and data values. We are going to create parameterized tests that will test the same method but with different values.

The Scenario

Let’s start with a simple method that calculates the total price of a product * quantity and then it applies the discount on the total price.

public static double calculate(double price,int quantity,double discount) 
{
    double totalPrice = price * quantity;
    double totalPriceWithDiscount = System.Math.Round(totalPrice - (totalPrice * discount/100),2);
    return totalPriceWithDiscount;
}

As simple as it looks, there is a lot of important other stuff to test here, like:

  • null’s
  • negative and zero inputs
  • exceptions/input validation handling
  • rounding

But we are not going to cover these here.

We are going to focus on the parameterized test and validating the mathematical correctness of the calculation method.

Without a parameterized test, we have this plain test.

[Test]
public void testCalculate() 
{
    Assert.AreEqual(100,MyClass.calculate(10,10,0));
}

This passes and, indeed, if the price of a product is 10, the quantity is 10, and we have zero discounts then the total price is 100.

The problem is that with this setup if we want to test different values and results we have to write a different test method for every different input.

The TestCase Attribute

We start by first converting the above test to a parameterized test using the TestCase attribute.

[TestCase(10,10,10,90)]
[TestCase(10,10,0,100)]
public void testCalculate(double price,int quantity,double discount,double expectedFinalAmount) 
{
    Assert.AreEqual(expectedFinalAmount,MyClass.calculate(price,quantity,discount)); 
}

Now, this method will run for every TestCaseannotation it has. A mapping will occur at runtime to the values we provided at the annotations and copied down to the method parameters. In our example, this test will run two times. We can pass reference types and value types.

Usually, the order of parameters goes by first providing the values and the last one is the expected result.

The TestCaseSource Attribute

For every different input, we have to add a TestCaseattribute at the top of the test method. To organize the code, and for reusability reasons, we are going to use the TestCaseSource attribute. We’re going to create a provider method and centralize the input data.

First, we create a provider method and then move and fill it with the data we want.

public static IEnumerable priceProvider() 
{
    yield return new TestCaseData(10,10,10,90);
    yield return new TestCaseData(10,10,0,100);
}

And also refactor the testCalculate method to use the priceProvider method.

[Test,TestCaseSource("priceProvider")]
public void testCalculate(double price,int quantity,double discount,double expectedFinalAmount) 
{
    Assert.AreEqual(expectedFinalAmount,MyClass.calculate(price,quantity,discount)); 
}

This is the same as having the TestCase attributes on top of the method.

We can also provide a different class for the provider methods to isolate and centralize the code in class/file level.

[Test,TestCaseSource(typeof(MyProviderClass),"priceProvider")]
public void testCalculate(double price,int quantity,double discount,double expectedFinalAmount) 
{
    Assert.AreEqual(expectedFinalAmount,MyClass.calculate(price,quantity,discount)); 
}

priceProvideris a static method inside MyProviderClass.

Extra Parameterization With the Help of the TestFixture Attribute

Let’s add one more step of parameterization with the help of TestFixture Attribute.Usually,TestFixture is a class attribute to mark a class that contains tests, on the other hand, one of the biggest features is that TestFixture can take constructor arguments. NUnit will create and test a separate instance for every input set.

Let’s assume that except for the final amount we test above, there is an extra amount applied depending on what category the product is, which could be category 1 or 2.

[TestFixture(typeof(int),typeof(double),1,5)]
[TestFixture(typeof(int),typeof(double),2,6.5)]
public class TestCharge
{
    T categoryType;
    X extraValue;
    public TestCharge(T t,X x) 
    {
        this.categoryType = t;
        this.extraValue = x;
    }
}

We know, in fact, that in category one the extra amount is 5 and in category two it’s 6.5.

We can now run all the tests again but also for every TestFixture we provided.

For example, we test the calculation also depending on the category.

[Test,TestCaseSource(typeof(MyProviderClass),"priceProvider")]
public void testCalculateCategory(double price,int quantity,double discount,double expectedFinalAmount) 
{
    Assert.AreEqual(expectedFinalAmount+(double)(object)this.extraValue,
                    MyClass.calculateCategory(price,quantity,discount,(int)(object)this.categoryType)); 
}

Final Words

Remember, what makes a good unit test is its simplicity, the ease of reading and writing, the reliability, not to be treated as an integration test, and it has to be fast.

The original and complete repository of code samples can be found here.

This article originally posted here

492 Replies to “Parameterized Test Example in .NET Core Using NUnit.”

  1. Pingback: custom keto
  2. Pingback: 토토사이트
  3. Pingback: live draw hk
  4. Pingback: Dekbedovertrekken
  5. Pingback: Cbd Capsules
  6. Pingback: prediksi hk
  7. Pingback: Buy CBD Flower UK
  8. Pingback: maricón
  9. Pingback: pr jobs
  10. Pingback: winnipeg used cars
  11. Pingback: 먹튀검증
  12. Pingback: Haier G7
  13. Pingback: 토토먹튀
  14. Pingback: news
  15. Pingback: Attitude Seeds
  16. Pingback: Paleo Diet
  17. Pingback: influensmi
  18. Pingback: poker99
  19. Pingback: data sgp
  20. Pingback: w88vn
  21. Pingback: filmaionline.net
  22. Pingback: guest
  23. Pingback: Pressure Washing
  24. Pingback: w88hello
  25. Pingback: uhynzeyl
  26. Pingback: 20mg cialis
  27. Pingback: viagra online
  28. Pingback: ventolin 50 mg
  29. Pingback: prednisolone 2mg
  30. Pingback: clomid late period
  31. Pingback: buy priligy reddit
  32. Pingback: goodrx diflucan
  33. Pingback: synthroid savings
  34. Pingback: neurontin tab
  35. Pingback: paxil forum
  36. Pingback: sildenafil usa
  37. Pingback: cymbalta overdose
  38. Pingback: vitamin d cymbalta
  39. Pingback: define cialis
  40. Pingback: drug finasteride
  41. Pingback: cialis otc status
  42. Pingback: cialis otc months
  43. Pingback: indian viagra
  44. Pingback: comprar viagra 100
  45. Pingback: buy cialis now
  46. Pingback: ed pills gnc
  47. Pingback: buy now
  48. Pingback: viagra song
  49. Pingback: buy ebay
  50. Pingback: 20mg low price
  51. Pingback: buy ebay
  52. Pingback: lovoo einloggen
  53. Pingback: 25 mg lisinopril
  54. Pingback: buy cialis ebay
  55. Pingback: cialis soft tablet
  56. Pingback: cialis 20mg usa
  57. Pingback: tadalafil 5 mg
  58. Pingback: fildena 50
  59. Pingback: viagra sample
  60. Pingback: fildena 50 mg
  61. Pingback: cialis effects
  62. Pingback: viagra for girls
  63. Pingback: stromectol 3mg
  64. Pingback: cialis canada
  65. Pingback: cialis ingredient
  66. Pingback: levitra 10 mg
  67. Pingback: lipitor 40 mg
  68. Pingback: losartan 100 mg
  69. Pingback: levitra 20mg
  70. Pingback: duloxetine hcl dr
  71. Pingback: cymbalta
  72. Pingback: bupropion 150 mg
  73. Pingback: generic celexa
  74. Pingback: bupropion 300 mg
  75. Pingback: flagyl antibiotic
  76. Pingback: supplements for ed
  77. Pingback: sildenafil online
  78. Pingback: cocaine and viagra
  79. Pingback: stromectol 0.5 mg
  80. Pingback: acyclovir
  81. Pingback: amoxicillin 500mg
  82. Pingback: what is cefdinir
  83. Pingback: cephalexin 500
  84. Pingback: zithromax cost uk
  85. Pingback: 5mg cialis cost
  86. Pingback: who makes viagra
  87. Pingback: daily viagra
  88. Pingback: cialis timeline
  89. Pingback: levitra medication
  90. Pingback: buy ivermectin
  91. Pingback: cialis from mexico
  92. Pingback: how to take cialis
  93. Pingback: otc viagra
  94. Pingback: viagra definition
  95. Pingback: cialis 2019
  96. Pingback: cialis daily pill
  97. Pingback: viagra cost
  98. Pingback: finasteride dosage
  99. Pingback: cat prednisolone
  100. Pingback: cialis 10mg india
  101. Pingback: viagra best price
  102. Pingback: sildenafil
  103. Pingback: plaquenil mexico
  104. Pingback: cialis usa
  105. Pingback: buy tadalafil
  106. Pingback: zithromax cost
  107. Pingback: regcialist.com
  108. Pingback: buy plaquenil uk
  109. Pingback: genic cialis
  110. Pingback: norvasc picture
  111. Pingback: ivermectin 6
  112. Pingback: sildenafil 100mg
  113. Pingback: effects of lipitor
  114. Pingback: cost of viagra
  115. Pingback: sildenafil generic
  116. Pingback: cialis 5 mg tablet
  117. Pingback: cialis daily
  118. Pingback: lilly cialis 5mg
  119. Pingback: cialis 20mg cheap
  120. Pingback: viagra cheap
  121. Pingback: 1
  122. Pingback: and duloxetine
  123. Pingback: viagrarover.com
  124. Pingback: canadian viagra
  125. Pingback: viagraherse.com
  126. Pingback: womens viagra
  127. Pingback: cialis 2.5 mg
  128. Pingback: doxycycline 100 mg
  129. Pingback: viagra otc mexico
  130. Pingback: ivermectin pills
  131. Pingback: cialis for sale
  132. Pingback: cialis 10mg
  133. Pingback: tonsillitis z pack
  134. Pingback: pour on ivermectin
  135. Pingback: salbutamol gsk
  136. Pingback: ed medications
  137. Pingback: cialis walmart
  138. Pingback: pills for erection
  139. Pingback: aperta
  140. Pingback: sildenafil 50 mg
  141. Pingback: best ed drugs
  142. Pingback: same day loan
  143. Pingback: cashino
  144. Pingback: cheap viagra usa
  145. Pingback: ivermectin 5
  146. Pingback: ivermectin 18mg
  147. Pingback: ivermectin 3mg
  148. Pingback: snorting viagra
  149. Pingback: prednisone 40 mg
  150. Pingback: chewable viagra
  151. Pingback: herb viagra
  152. Pingback: viagra pour homme
  153. Pingback: cheap viagra
  154. Pingback: natural viagra
  155. Pingback: blue pill viagra
  156. Pingback: whats viagra
  157. Pingback: viagra en ligne
  158. Pingback: goodrx sildenafil
  159. Pingback: viagra foods
  160. Pingback: valtrex prices
  161. Pingback: viagra cialis
  162. Pingback: women viagra
  163. Pingback: buy viagra 50 mg
  164. Pingback: viagra usa
  165. Pingback: plaquenil pill
  166. Pingback: female viagra
  167. Pingback: sildenafil prices
  168. Pingback: stromectol drug
  169. Pingback: fildena
  170. Pingback: ivermectin humans
  171. Pingback: male ed drugs
  172. Pingback: fake viagra pills
  173. Pingback: viagra pro
  174. Pingback: cialis tadalafil
  175. Pingback: cialis online
  176. Pingback: daily cialis pills
  177. Pingback: cialis price
  178. Pingback: vietnamese viagra
  179. Pingback: Biltricide
  180. Pingback: navarro pharmacy

Comments are closed.