13.5. Lab: Exceptions, Debugging & Testing#

Practice exercises for try/catch/finally, debugging workflows, and unit testing.

13.5.1. Your Tasks#

  1. Implement this unit testing project.

  2. Add one method in the application and one corresponding test in the test project.

  3. As usual, prepare the assignment using a Word document with screenshots (code and execution with path and username) and your annotations.

13.5.2. Preparing Project#

The idea of TDD is to write tests first, so that you will be focused with the requirements and not to be distracted by your own coding. That’s why we start with simple test cases in the test project to test the units in the application project. After you make sure the application tests can pass, you then improve the units (methods, classes) in the application project.

The process of creating a unit test involves several steps:

  1. Create a lab folder, call it Ch13SelectedTopicsLab, inside [USERNAME]\workspace\introcscs\.

  2. Create a solution folder:

    1. Inside Ch13SelectedTopicsLab, create a folder UnitTestProject1 and run:

      dotnet new sln
      
    2. To open the solution in VS Code: ViewCommand Palette.NET: Open Solution.

  3. Create an application project folder MathApp, and a test project folder MathAppTest inside UnitTestProject1.

  4. Initialize them:

    cd MathApp && dotnet new console
    cd ../MathAppTest && dotnet new mstest
    
  5. Add both to the solution and link them:

    dotnet sln add MathApp
    dotnet sln add MathAppTest
    dotnet add MathAppTest reference MathApp
    

13.5.3. Preparing Code#

Revise Program.cs in MathApp with a BasicMath class containing 4 arithmetic methods, and revise UnitTest1.cs in MathAppTest with corresponding [TestMethod] test methods. Run dotnet test inside UnitTestProject1 to verify.

13.5.4. Run Testing in VS Code#

You can also run tests visually using the C# Dev Kit extension — build the test project in Test Explorer to make tests appear in the Activity Bar’s Testing section.

Footnotes