C#. Console Application. Example of creating a Unit-test in MS Visual Studio 2010




Example of creating a Unit-test in MS Visual Studio 2010 – C#

This topic describes the step-by-step process of creating the simplest unit test in Microsoft Visual Studio 2010 (C#) for Console Application. Using this example, you can learn how to create your own Unit-tests. The example also demonstrates how to use the Assert class for testing.


Contents


Search other websites:

Task

For a Console Application type application, develop a Unit test that tests the Min() function. For the Min() function, set the TestMin() test method. Test the functions result.

 

Instructions

1. Create an application using the Console Application template

Run MS Visual Studio 2010. To create a project using the Console Application template, you need to call the following command sequence:

File -> New -> Project...

As a result, the New Project window opens. In the window, select the “Console Application” template as shown in Figure 1. The template is selected in the Visual C# tab.

C#. Windows Forms. The "New Project" window. Selecting the "Console Application"

Figure 1. The “New Project” window. Selecting the “Console Application”

 

2. Preparing the text of the Program.cs module

2.1. Adding the Min() function

In the body of the Program class, you need to add the text of the Min() function. The function is declared as public and static. The text of the Min() function

C#. The MS Visual Studio window, the module "Program.cs"

Figure 2. The MS Visual Studio window, the module “Program.cs”

 

2.2. Make the Program class public

In order to access the Min() function of the Program class, you need to make this class public. To do this, before the class declaration, you need to set the public keyword.

...

namespace MinApp
{
    public class Program
    {
        // методы класса
        // ...
    }
}

...

After that the tested program is ready.

 

3. Listing of the program under test

At the moment the program code of the program under test is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MinApp
{
    public class Program
    {
        public static int Min(int a, int b, int c)
        {
            int min = a;
            if (min > b) min = b;
            if (min > c) min = c;
            return min;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Demo of Unit-testing in C#.");
        }
    }
}

Because this program will be tested from another testing module, then in the Main() function, you do not need to type anything else. Since, in accordance with the condition of the task, you need to test the operation of the Min() function. And this will already be done from the testing module. At the moment our program is ready for testing.

 

4. Creating a test

The test is created by a separate project in the Solution. The program you are testing does not know about this. The test program that will test calls the functions of the program that is being tested. In our case, the test program will call the function

int Min(int, int, int);


 

4.1. Adding a new project to the solution

For this solution, a new project is added using the command

File->Add->New Project...

The window for creating a new project is shown in Figure 3.

C#. Windows Forms Application. The window for creating a project of type Test Project

Figure 3. The window for creating a project of type Test Project

In the window you need to select the templates group

Visual C# -> Test

From the displayed templates, the project template “Test Project” is selected. The “Name” field indicates the name of the project that will test our program. You need to set, for example, TestMinApp. The project is located in a separate folder “E:\Test\MinApp”.

C#. The "UnitTest1.cs" file. The Solution Explorer window with the TestMinApp and MinApp projects displayed

Figure 4. The “UnitTest1.cs” file. The Solution Explorer window with the TestMinApp and MinApp projects displayed

 

4.2. Structure of Solution

As you can see in Figure 4, Solution Explorer displays the Solution Items structure, which contains two projects:

  • the MinApp project. This is a project created using the “Console Application” template with the Min() function to be tested;
  • the TestMinApp project. This project is designed to test the functions of the MinApp project. The program code that tests the Min() function will be added to the project file UnitTest1 of the TestMinApp project.

Both projects can be executed independently of each other.

 

4.3. Program code of “UnitTest1.cs” file. Attributes [TestMethod] and [TestClass]

In the TestMinApp project, the UnitTest1.cs test file is of primary interest. This file contains methods that will test the functions of the MinApp project. The TestMinApp project can contain any number of files that contain tests (for example, UnitTest2.cs, UnitTest3.cs, etc.).

Program code of “UnitTest1.cs” file, generated by MS Visual Studio 2010, is as follows:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestMinApp
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class UnitTest1
    {
        public UnitTest1()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;
        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void TestMethod1()
        {
            //
            // TODO: Add test logic here
            //
        }
    }
}

As you can see from the above code, the file contains a class named UnitTest1. The class involves a public method named TestMethod1().Before implementing the TestMethod1() method, the [TestMethod] attribute is placed. This means that in the body of the method need to write code that will test the functions of MinApp project.

In the class, you can enter any number of methods that will test different functions from different modules. The main thing is that these methods where noticed by the attribute [TestMethod].

 

4.4. Making changes in the text UnitTest1.cs module. Changing the name of the testing method

You can change the method names and add new methods that are marked with the [TestMethod] attribute in the UnitTest1.cs module. With this in mind, in UnitTest1.cs, the TestMethod1() method should be renamed to TestMin().

After the changes are made, the abbreviated text of UnitTest1.cs file module will look like:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestMinApp
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class UnitTest1
    {
        ...

        [TestMethod]
        public void TestMin()
        {
            //
            // TODO: Add test logic here
            //
        }
    }
}

 

4.5. Connecting the MinApp project to the TestMinApp project

To access the Min() function (the MinApp project) from the TestMinApp project, you need to mount the namespace in which this function is declared.

To do this, you first need to call the context menu for the TestMinApp project. Then in the context menu, you need to call the command “Add Reference …” (Figure 5).

C#. Unit-test creating. The "Add Referencse..." command

Figure 5. The “Add Referencse…” command

As a result, the “Add Reference” window opens, in which you select the MinApp project.

C#. Unit-test creating The "Add Reference" window. MinApp project connection

Figure 6. The “Add Reference” window. MinApp project connection

After the performed actions, the MinApp project functions will be available for use in the TestMinApp project.

C#. Windows Forms Application. The "References" tab with the connected MinApp project

Figure 7. The “References” tab with the connected MinApp project

 

4.6. Modification of UnitTest1.cs module text
4.6.1. Adding the MinApp namespace to UnitTest1.cs

In this step, you need to add the MinApp namespace to UnitTest1.cs using the ‘using’ directive:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using MinApp;

namespace TestMinApp
{
    ...
}

 

4.6.2. Text of the TestMin() method

In the text of the TestMin() method, you need to enter the following code:

...

[TestMethod]
public void TestMin()
{
    //
    // TODO: Add test logic here
    //
    int min;
    min = Program.Min(3, 4, 5);
    Assert.AreEqual(2, min);
}

...

 

4.7. The text of UnitTest1.cs module

The text of all UnitTest1.cs module is as follows:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using MinApp;

namespace TestMinApp
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class UnitTest1
    {
        public UnitTest1()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;
        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void TestMin()
        {
            //
            // TODO: Add test logic here
            //
            int min;
            min = Program.Min(3, 4, 5);
            Assert.AreEqual(2, min);
        }
    }
}

 

5. Run the test and checking testing result

In Microsoft Visual Studio 2010 for Unit-tests, a special menu ‘Test’ is implemented.

To run the test, you must select one of the commands

Test -> Run -> Tests in Current Context

or

Test -> Run -> All Tests in Solution

as shown in Figure 8.

C#. Unit-test creating. Calling the test command and viewing the result

Figure 8. Calling the test command and viewing the result

After starting the test, the result can be viewed on the left in the Test Explorer window. As can be seen from the Figure 8, the test is not passed. This is logical, because in the function Assert.AreEqual() we compare the numbers 2 and 3, which are different. Here the number 2 is specially entered instead of the number 3.

If instead of number 2 you enter the correct answer – number 3 (minimum between 3, 4, 5), then the test will be submitted (Figure 9). In this case, the text of the TestMin() method will be as follows:

...

[TestMethod]
public void TestMin()
{
    //
    // TODO: Add test logic here
    //
    int min;
    min = Program.Min(3, 4, 5);
    Assert.AreEqual(3, min);
}

...

The result window is shown in Figure 9.

C#. Unit-test creating. Test result for the case when you enter the correct answer

Figure 9. Test result for the case when you enter the correct answer

Now we can conclude that the Min() function works correctly for this case.

 

6. The result. Interaction between projects

In this task, the solution involves two projects. One MinApp project contains the Min() function to be tested. The second TestMinApp project contains test methods. In Microsoft Visual Studio 2010, each of the projects is run using various menu commands. So, the MinApp project is run in the standard way from the Run menu. And the TestMinApp project is launched from a special ‘Test’ menu.

 


Related topics