HTML Dropdown

Tuesday, 6 October 2015

How to: Create and Run a Unit Test



Check that your code is working as expected by creating and running unit tests. It’s called unit testing because you break down the functionality of your program into discrete testable behaviors that you can test as individual units. Visual Studio Test Explorer provides a flexible and efficient way to run your unit tests and view their results in Visual Studio. Visual Studio installs the Microsoft unit testing frameworks for managed and native code. Use a unit testing framework to create unit tests, run them, and report the results of these tests. Rerun unit tests when you make changes to test that your code is still working correctly. When you use Visual Studio Enterprise, you can run tests automatically after every build.
Unit testing has the greatest effect on the quality of your code when it’s an integral part of your software development workflow. As soon as you write a function or other block of application code, create unit tests that verify the behavior of the code in response to standard, boundary, and incorrect cases of input data, and that check any explicit or implicit assumptions made by the code. With test driven development, you create the unit tests before you write the code, so you use the unit tests as both design documentation and functional specifications.
You can quickly generate test projects and test methods from your code, or manually create the tests as you need them. When you use IntelliTest to explore your .NET code, you can generate test data and a suite of unit tests. For every statement in the code, a test input is generated that will execute that statement.

Test Explorer can also run third-party and open source unit test frameworks that have implemented Test Explorer add-on interfaces. You can add many of these frameworks through the Visual Studio Extension Manager and the Visual Studio gallery.

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



No comments:

Post a Comment