Click here to Skip to main content
Click here to Skip to main content
Go to top

Creating Unit tests for your c# code

, 7 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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.
  
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. 

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...".

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.

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

  /// <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

        [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.

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 :

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:

    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:

 [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)

Share

About the Author

@AmitGajjar
Software Developer (Senior)
India India
No Biography provided

Comments and Discussions

 
QuestionMail4Net is worth a look PinmemberMember 1100715011-Aug-14 22:18 
QuestionNot Getting option "Create Unit Test" Pinmemberrathor040710-Aug-14 20:20 
GeneralRe: Not Getting option "Create Unit Test" Pinprofessional@AmitGajjar11-Aug-14 3:52 
Questionhelp PinmemberMember 100295635-May-13 5:28 
AnswerRe: help Pinprofessional@AmitGajjar29-Jul-13 6:03 
QuestionGenerate Unit Test link missing in VS 2012 Pinmemberanjana_z15-Oct-12 23:12 
AnswerRe: Generate Unit Test link missing in VS 2012 Pinmember@AmitGajjar15-Oct-12 23:14 
GeneralRe: Generate Unit Test link missing in VS 2012 PinmemberArsine531-Oct-12 10:34 
GeneralRe: Generate Unit Test link missing in VS 2012 Pinmember@AmitGajjar31-Oct-12 19:12 
GeneralMy vote of 5 PinmemberTrilok Arora5-Oct-12 6:01 
GeneralRe: My vote of 5 Pinmember@AmitGajjar5-Oct-12 7:20 
GeneralMy vote of 4 PinmvpKanasz Robert28-Sep-12 5:56 
GeneralRe: My vote of 4 Pinmember@AmitGajjar28-Sep-12 17:58 
GeneralMy 4: Good start, may eventually need some elaboration... PinmemberAndreas Gieriet7-Jun-12 12:08 
GeneralRe: My 4: Good start, may eventually need some elaboration... Pinmemberamitgajjar7-Jun-12 18:04 
Thanks
GeneralMy vote of 1 Pinmembermayur csharp G7-Jun-12 0:04 
GeneralRe: My vote of 1 Pinmemberamitgajjar7-Jun-12 0:46 
GeneralMy vote of 1 PinmemberMember 88776636-Jun-12 23:28 
GeneralRe: My vote of 1 Pinmemberamitgajjar6-Jun-12 23:30 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 7 Jun 2012
Article Copyright 2012 by @AmitGajjar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid