Setting up GitHub actions with PostgreSQL & C# .Net Core.
Once you committed your code to GitHub setup CI by using GitHub Actions - click on Actions in your GitHub repository.
Search for : `.NET By GitHub Actions Build and test a .NET or ASP.NET Core project.
Click on: Setup this workflow
Create a services section just below runs-on
in your dotnet.yml
file.
services:
postgres:
image: postgres:latest
env:
POSTGRES_USER: counter
POSTGRES_PASSWORD: counter123
POSTGRES_DB: counter_app
ports:
- 5432:5432
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
Change the POSTGRES_
variables as needed.
Add a step to run a database script to create the needed tables.
- name: create postgresql tables
run: PGPASSWORD=counter123 psql -h localhost -U counter -d counter_app -a -f ./GreetCount/sql/tables.sql
Add an environment variable that matches the database configuration you did earlier to the Test
task.
- name: Test
run: dotnet test --no-build --verbosity normal
env:
PSQLConnectionString: Host=localhost;Username=counter;Password=counter123;Database=counter_app
Use the Environment.GetEnvironmentVariable
method to read a variable from an environment variable:
static string GetConnectionString() {
// read the connection string from an environment variable...
// this make is possible for this test to run on Git Hub Actions
var theCN = Environment.GetEnvironmentVariable("PSQLConnectionString");
if (theCN == "" || theCN == null) {
theCN = cn;
}
return theCN;
}