Last updated on 2022-07-07
Now that we have a unit test for our project, let’s add a GitHub Action to run those unit tests when we commit changes to the repository – and tell you if those changes broke any unit tests.
Ideally, we would always run our unit tests before pushing a change to the repository, but we’re all human and sometimes we forget. By creating a GitHub Action, we’ll be sure the tests are always run.
Creating the GitHub Action
Go to your project’s page on GitHub and click the “Actions” link.
The instructions for the action are listed in a YML file. This file includes:
- What events trigger the action (in our case, pushing changes to the master branch of the repository)
- What environment is needed to run the action (Windows, Ubuntu, etc.)
- What steps to perform in the action (build the solution and run the unit tests)
name: .NET on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: windows-latest steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v2 with: dotnet-version: 6.0.x - name: Restore dependencies run: dotnet restore - name: Build run: dotnet build --no-restore - name: Test run: dotnet test --no-build --verbosity normal
There are two important things that may need to be changed from the default action we started with.
The “runs-on” value determines what environment to run this action on. If your building a cross-platform application – a .NET Core or .NET 5/6 application that does not use WPF or WinForms – you can use “ubuntu-latest”. If the solution is in .NET Framework, or uses WPF or WinForms, you need to use “windows-latest”.
You could put specific versions of Windows or Ubuntu if you don’t want to use the latest. But we’ll stick with the basics for now.
You may also need to change the “dotnet-version” value.
Adding the GitHub Action to the repository
After creating the action YML file, we need to add it to the solution.
If we go back into Visual Studio and pull down the changes afterwards, we’ll see the action’s YML file in a .github\workflows directory. So, we can edit the steps of the action on our local computer and push the changes to our repository – in case we want to change the behavior of the action in the future.
Running the GitHub Action
We specify to run this action whenever code is pushed to the master branch, or a pull request is made against the master branch, (see lines 4-7 of the YML file).
To test this, make a change to your solution, push the changes to the master branch, then refresh the repository’s “Actions” page. You should see the action running, followed by a green checkmark (if the action succeeded) or a red check (if the action encountered an error).
Now you can add actions to automatically run your unit tests on checkins. You can build more complex actions, and I’ll probably demonstrate those in future videos.
Please let me know if you have any questions, or if you’d like to see a video on how to create any specific actions.