.NET: Running Test Cases against database in GitLab CI/CD [Part 2]

·

·

In our previous article, we’ve seen how to run the test cases against a database in our local environment using .NET 5 + EF Core + xUnit + MySql.

In this article let’s see how we can run the same setup in GitLab CI/CD on raising a merge request for continuous integration & deployment.

Add Gitlab CI/CD yml file:

In order to configure ci/cd in GitLab, we need to write a config file that looks like below.

.gitlab-ci.yml

gitlab-ci.yaml

The configuration is simple.

variables:

  • AppSettings__MySqlConnectionString: This is the important variable which will be read by our test case project. Remember we added the AddEnvironmentVariable() in the part 1. Read more about the configuration environment variables in ASP.NET Core here.
ConfigurationHelper.cs

image:

  • We’re using the mcr.microsoft.com/dotnet/sdk:5.0 base image which we can use to build and run the dotnet project.

services:

  • mysql:5.7.34This is the MySql docker image that will be used to run the MySql container before our test is run. This container will read MYSQL_ROOT_PASSWORD variable & set it as password for root user.

only: -merge_requests

  • This is an option to say that the test case should run only when the merge request is raised.

script:

  • This is the place where we write our commands. So, to run test cases using dotnet CLI, we need to use dotnet test in the test project directory.

Configuring Secrets:

We shouldn’t explicitly hardcode the password for security reasons. So we can add the variable under the project settings as described below.

Under your GitLab project repository, goto Settings -> CI/CD -> Variables -> Add new variable called ‘MYSQL_PASS’. Now, this variable can be used within the .gitlab-ci.yml file.

GitLab Runner Configuration:

Make sure the runners are registered & enabled for the project. Here, we’re using the shared runners provided by GitLab. You can register your own runner as well.

. . .

Now it’s testing time! Let’s raise merge request:

So far, we’ve wired up all the necessary things. Now, whenever the merge request is raised, test case is run & the status is shown within the merge request.

Pipeline in progress when the merge request is raised

Pipeline logs

Merge Request with pipeline succeeded

What we’ve seen here is fairly easy to setup. But there are tons of options to configure based on project needs. I hope this article helps you to get started exploring all the options available.

Repohttps://gitlab.com/soundar.a/dotnet-unit-testing-with-database

Keep exploring. Happy Coding 🙂

Author



Leave a Reply

Your email address will not be published. Required fields are marked *