Click here to Skip to main content
15,867,308 members
Articles / DevOps / Testing

Creating Unit tests for your c# code

Rate me:
Please Sign up or sign in to vote.
4.52/5 (55 votes)
7 Jun 2012CPOL4 min read 519.3K   74   23
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)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHello Amit Pin
vlad88alex20-Feb-18 22:27
vlad88alex20-Feb-18 22:27 
QuestionGood one Pin
vatsa_gaurav23-Feb-16 20:03
vatsa_gaurav23-Feb-16 20:03 
GeneralMy vote of 3 Pin
raviteja chekuri29-Oct-14 2:20
raviteja chekuri29-Oct-14 2:20 
QuestionUnit Tests should <b>not</b> access privates Pin
Andrew Phillips22-Oct-14 19:55
Andrew Phillips22-Oct-14 19:55 
AnswerRe: Unit Tests should <b>not</b> access privates Pin
AmitGajjar23-Oct-14 6:02
professionalAmitGajjar23-Oct-14 6:02 
QuestionNot Getting option "Create Unit Test" Pin
rathor040710-Aug-14 20:20
rathor040710-Aug-14 20:20 
GeneralRe: Not Getting option "Create Unit Test" Pin
AmitGajjar11-Aug-14 3:52
professionalAmitGajjar11-Aug-14 3:52 
Questionhelp Pin
Member 100295635-May-13 5:28
Member 100295635-May-13 5:28 
AnswerRe: help Pin
AmitGajjar29-Jul-13 6:03
professionalAmitGajjar29-Jul-13 6:03 
QuestionGenerate Unit Test link missing in VS 2012 Pin
anjana_z15-Oct-12 23:12
anjana_z15-Oct-12 23:12 
Generate Unit Test link missing in VS 2012

Thanks.
AnswerRe: Generate Unit Test link missing in VS 2012 Pin
AmitGajjar15-Oct-12 23:14
professionalAmitGajjar15-Oct-12 23:14 
GeneralRe: Generate Unit Test link missing in VS 2012 Pin
Arsine531-Oct-12 10:34
Arsine531-Oct-12 10:34 
GeneralRe: Generate Unit Test link missing in VS 2012 Pin
AmitGajjar31-Oct-12 19:12
professionalAmitGajjar31-Oct-12 19:12 
GeneralMy vote of 5 Pin
Trilok Arora5-Oct-12 6:01
Trilok Arora5-Oct-12 6:01 
GeneralRe: My vote of 5 Pin
AmitGajjar5-Oct-12 7:20
professionalAmitGajjar5-Oct-12 7:20 
GeneralMy vote of 4 Pin
Kanasz Robert28-Sep-12 5:56
professionalKanasz Robert28-Sep-12 5:56 
GeneralRe: My vote of 4 Pin
AmitGajjar28-Sep-12 17:58
professionalAmitGajjar28-Sep-12 17:58 
GeneralMy 4: Good start, may eventually need some elaboration... Pin
Andreas Gieriet7-Jun-12 12:08
professionalAndreas Gieriet7-Jun-12 12:08 
GeneralRe: My 4: Good start, may eventually need some elaboration... Pin
AmitGajjar7-Jun-12 18:04
professionalAmitGajjar7-Jun-12 18:04 
GeneralMy vote of 1 Pin
mayur csharp G7-Jun-12 0:04
mayur csharp G7-Jun-12 0:04 
GeneralRe: My vote of 1 Pin
AmitGajjar7-Jun-12 0:46
professionalAmitGajjar7-Jun-12 0:46 
GeneralMy vote of 1 Pin
Member 88776636-Jun-12 23:28
Member 88776636-Jun-12 23:28 
GeneralRe: My vote of 1 Pin
AmitGajjar6-Jun-12 23:30
professionalAmitGajjar6-Jun-12 23:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.