The previous post in this series ended with that we made our test project use a real Postgres database. When we pushed our code to GitHub, our action failed (as expected) since the tests could not connect to any database. Let's fix that!

Since I have all of my personal projects on GitHub I tend to also use GitHub actions for all my continous integration needs.

Currently, my workflow file looks like this:

name: .NET

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
jobs:
  build:
    name: Build and Test
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 7.0.x
    - name: Build and Test
      run: dotnet test -c Release --verbosity minimal

As you can see, it's very basic. All it does is checking out the code and then running dotnet test on the solution.

Right now, all of my tests fails with the following exception:

Error Message:
   Npgsql.NpgsqlException : Failed to connect to 127.0.0.1:5432
---- System.Net.Sockets.SocketException : Connection refused

To fix this, we need to ensure that a Postgres database is available when running the tests.

Fortunately, it's very simple when using GitHub Actions. All I need to do is to add the following to my workflow file:

services:
  postgres:
    image: postgres:15
    env:
      POSTGRES_USER: my_weather_app
      POSTGRES_PASSWORD: my_password
    options: >-
      --health-cmd pg_isready
      --health-interval 10s
      --health-timeout 5s
      --health-retries 5
    ports:
      - 5432:5432

Here I'm using the official Postgres docker image. I'm configuring the username and password to match what's specified in my MyWeatherAppApiTestConfiguration file. Lastly, I'm exposing the 5432 port so that my tests can connect via localhost when running in the GitHub action context.

That's really all we need to do. The complete workflow file looks like this:

name: .NET

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
jobs:
  build:
    name: Build and Test
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_USER: my_weather_app
          POSTGRES_PASSWORD: my_password
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          # Maps tcp port 5432 on service container to the host
          - 5432:5432
    steps:
    - uses: actions/checkout@v3
    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 7.0.x
    - name: Build and Test
      run: dotnet test -c Release --verbosity minimal