Posted on Leave a comment

Run Unit tests for .NET applications – Azure DevOps

In this article I will demonstrate how one can write and integrate Unit tests on .NET solutions and automate the testing procedure through Azure DevOps.

For my scenario I have a simple Console App .NET application inside a solution with the name ConsoleApp1. This solution includes also another project, the TestProject1 which is of type MSTest project.

My ConcoleApp only contains a simple function that adds two numbers. The code is shown below as well as the solution structure.

The unit test methods are also simple and will verify whether the add function works properly. The TestMethod1 will verify if the int input is correct, and the second one will fail as I try to evaluate a string with an int value.

In order to build the tests you should right click on TestProject1 and press run tests.

By checking the output we can verify that the UnitTest1 was successful in comparison with UnitTest2 which failed.

Lets now examine how to automate the procedure of the build and test using Azure DevOps. The first step is to upload the solution on a source control site and integrate Azure DevOps with it. I have already documented the procedure on a previous article build-pipeline-for-net-solutions-using-cake2-azure-devops

My pipeline contains two stages, one for the build of the project and one for the run of unit tests. The code is available below:

  vmImage: ubuntu-latest

trigger: none
pr: none 


  - stage:
    displayName: Build .NET application
      - job:
        displayName: build job
          - task: UseDotNet@2
            displayName: Use .NET6 to build
              version: '6.0.x'
              includePreviewVersions: true
          - task: DotNetCoreCLI@2
            displayName: Building Visual studio solution
              command: 'build'
              projects: '**/*.csproj'
              arguments: '--configuration debug'

  - stage: 
    displayName: Run unit tests
      - job:
        displayName: unit tests job
          - task: DotNetCoreCLI@2
            displayName: Run Visual studio tests
              command: test
              projects: '**/*Test*/*.csproj'
              arguments: '--configuration debug'

As you can verify the tests stage failed because of the unit test that was not successful.

Azure DevOps also can give you an overview of how many tests succeeded. In my case I had 50% success rate because 1 out of 2 tests failed.

By pressing the 50% tests button you can also get a detailed review of the tests.

In more detail the method that fails is TestMethod2 and the exact message points to the comparison between the int and string values.

Video tutorial on YouTube:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.