Parameterized unit tests in MS test framework

Earlier, In MS test framework, we do not have any options to create Parameterized unit tests. So all we have to do is we have to write multiple unit test cases with same code. See below example which dictate this situation.

Example: We have a string and we need to change its case from lower to upper. Input: “test case” then output should be “TEST CASE” and if this string is empty then our function should return “EMPTY” in upper case. Lets write function for this requirement in C#.

Businee logic function

Now, lets write test cases for this function. We need to write at least three test cases to for this function. 1) str with empty value, 2) str with null value and 3) str with some valid value.

TestcaseResult

For same condition, we have created two unit test cases. In production code, we have seen many times we are doing this thing.

Recently, Microsoft has launched MSTest V2. To use this V2, all you need to do is upgrade your existing V1 project to V2. For that, install these two nuget packages: MsTest.TestAdapter & MsTest.TestFramework. After installing nuget packages, our test code will looks like below.

DataRowInput

Changes:

  1. Attributes has been changed from TestMethod to DataTestMethod.
  2. We’ve provided input in terms of DataRow attribute and that input will be passed as parameter to test method. You can also pass result value into parameter and you can check it in Assert statement.

For each DataRow item, same test case will be executed. In above case, above test case will be executed twice as we have applied two inputs.

Happy testing!

Leave a Reply

Your email address will not be published. Required fields are marked *