67465364_491902344708962_1591338503323516928_n.jpg

Hi.

Welcome to my blog. I document my ideas and productivity hacks.

.NET Core On Windows - How to execute unit test before I commit?

.NET Core On Windows - How to execute unit test before I commit?

Making sure that your code works it is always a great idea, automating that process is even better, and here is how you can do it in 3 easy steps.

1. Locating your git hooks folder

To execute your unit test before you commit your code, git has something called "git hooks." Git hooks are scripts that Git executes before or after events such as commit, push, and receive. But for this particular case, we will be using the commit event.

Locate your .git\hooks folder under your repository root folder.

For example for my EBasket project located at:

C:\Users\FDiaz\Development\EBasket

The git hooks folder should be:

C:\Users\FDiaz\Development\EBasket\.git\hooks

2. Adding a pre-commit script

If you are using Windows when executing git hooks scripts, it is required to have sh.exe installed (it usually gets installed when you install git).

a) Go to your git hooks folder

b) Locate the pre-commit file (or create if it does not exists)

c) Place this script inside that file (make sure you modify the script to point to your unit test csproj)

#!/bin/sh
exec dotnet test "./UnitTests/UnitTests.csproj" --filter "Category!=Integration"

if [ $? -ne 0 ]; then
echo "Tests must pass before commit!"
exit 1
fi

Notes: This script is executing the dotnet test command using desired test project to be executed. For more info on how to use --filter flag see https://docs.microsoft.com/en-us/dotnet/core/testing/selective-unit-tests

3. Executing the script

Commit some code!

Now every time you commit your unit test will run before commiting to your local branch. If your tests don't pass your commit won't be completed. Cheers!

Unboxing .NET Core - Integration Tests for Request/Response Pipeline

Unit Testing with AutoFixture and xUnit in .NET Core