Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / DevOps / testing

Creating Unit tests for your c# code

4.52/5 (55 votes)
7 Jun 2012CPOL4 min read 524.7K  
This test case is intended for understanding of how useful automated Unit tests

Introduction

When we are creating a C# library (API consumed by other applications) we are not sure what could be the possible uses of it by the application developer. They may pass incorrect argument information to our API functions. To validate all the scenarios we need to create code that will check and validate our API methods.

Sometimes we need to modify our methods and we do not have time to do smoke testing. In such scenarios, if we have an Automated Unit Test then we can easily check if anything breaks. To successfully validate our methods/Class, we need to achieve more code coverage for our code.

Using the code  

Here we will see how our code could be tested using a Unit Test Framework. I have created a sample method for explaining the testing framework. Check the below API method.
C#
public class ApplicationCodeClass
    {
        public string combineArrayStringWithSpace(string[] stringArray)
        {
            string str = default(string);

            foreach (string item in stringArray)
            {
                str += item + " ";
            }

            return str.Trim();
        }
    }  

Now let's see how many possible errors have been done by the API consumer...!!!!

1) stringArray may be null/Empty

2) One of the element of stringArray contains whitespace

3) Positive scenario when everything is good and we need to check our expected behavior.

There may be more possibility are there but let's consider above three scenario and we need to check whether our API method can handle this scenario or not. We need to check how many Rules get passed from our Automated Unit Test.

Create your First Unit Test(Step by Step)

Once you have done with your API development you can create your Developer test cases to verify your code. I am using Visual Studio 2010 Ultimate version. So don't know whether below option appear for you or not. But you can Use Microsoft.VisualStudio.QualityTools.UnitTestFramework namespace for creating Unit Test. 

Image 1

Now the next step is to create Automated Unit Test cases. Right click on your code file and that will show you option for "Create Unit Tests...".

Image 2

After selecting above option, you will be prompt for the choosing methods to create your automated test cases. Visual Studio will create some of the possible scenario with its own way. below is the snapshot for choosing your methods to create unit test. later will also see how we can create it manually.

Image 3

As you can see in the Output Project "UnitTestProject" is available(in my case). you will not see such project there. when you will click on the OK button you will be prompt to enter project name and project will be created.

Automated created test method will looks like

C#
/// <summary>
      ///A test for combineArrayStringWithSpace
      ///</summary>
      [TestMethod()]
      public void combineArrayStringWithSpaceTest()
      {
          ApplicationCodeClass target = new ApplicationCodeClass(); // TODO: Initialize to an appropriate value
          string[] stringArray = null; // TODO: Initialize to an appropriate value
          string expected = string.Empty; // TODO: Initialize to an appropriate value
          string actual;
          actual = target.combineArrayStringWithSpace(stringArray);
          Assert.AreEqual(expected, actual);
          Assert.Inconclusive("Verify the correctness of this test method.");
      }

Let's create our own Test Method

C#
[TestMethod]
public void PossitiveSchenarioForChecking_combineArrayStringWithSpace()
{
    string expectedResult = "Today is the wonderful day of my life";
    string[] actualStringArray = new string[] { "Today", "is", "the", "wonderful", "day", "of", "my", "life" };
    ApplicationCodeClass appObject = new ApplicationCodeClass();

    string actualResult = appObject.combineArrayStringWithSpace(actualStringArray);
    Assert.AreEqual<string>(expectedResult, actualResult);
}

As previously we have mention 3 possible scenario of using our API method. VisualStudio automated test case covers our 1st scenario and above test case will fulfill our 3rd scenario. the same way you can create 2nd scenario by passing whitespace in actualStringArray variable in above test method.

Image 4

Type of Test Cases

We can create functional test cases as well as Unit Test cases on our C# library code.

Functional Test Cases :

1) it will check the functionality and behavior of our methods.

2) it will also check if the function should not misbehave if we are passing incorrect argument to the function/methods.

3) we are covering the "What it should not do ?". it is also called Negative Functional test case.

4) we are covering the "What it should do?". it is also called Positive Functional test case.

Unit Test Cases:

1) we are covering each and every unit of code in unit test case. As a tester, we are responsible for checking if our most of the code is covered under Unit Test cases.

as an Example :

C#
if(Textbox1.Text == "ABC")
{
Response.Write("ABC is typed");
} 
else
{
Response.Write("ABC is not typed"); 
} 

in above code if we are checking the function with only TextBox1 with "ABC" as text then our all code will not cover. we also need to test with text value without "ABC" as text. then only we can say our code is 100% covered by our test cases.

Access Private variable to test Unit of code

My class code:

C#
public class sampleClass
{
    private int _classid;
    private string _name;
    public sampleClass()
    {}
    public sampleClass(int classId,string Name)
    {
        this._classid = classId;
        this._name = Name;
    }
}

My Test Method for accessing private variable:

C#
[TestClass]
   public class MyTestClass
   {
       [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
       public void MyTestMethod()
       {
           sampleClass newSampleClass = new sampleClass(2, "Amit Gajjar");
           Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject pobject = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject(newSampleClass);

           Assert.AreEqual<int?>(2, pobject.GetFieldOrProperty("_classid") as int?);
           Assert.AreEqual<string>("Amit Gajjar", pobject.GetFieldOrProperty("_name") as string);
       }
   }

From above test case you can see the last two Assert methods. we are able to access _classid and _name private variable from our assembly class.  By this way we can make sure that our class private variable are set properly as per our expectation. if this simple example is not clear your idea about why should we need to check private variable then consider the example when we have convertor class to convert Unit of temperature. If we are passing temperature in celsius then it should convert it back to Fahrenheit. At that time if our class get changed or if it is giving incorrect result then test engineer can catch that bug.

Last Words  

Hope this article will help you to create test cases.  your all suggetions are welcome and appriciated.



License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)