首頁 GitHub Actions and Workflows
文章
Cancel

GitHub Actions and Workflows

建立一個簡單的Github Action

建立Github專案

備註:開源專案是免費使用,私有專案是付費使用

Desktop View

本地讀取專案

Desktop View

建立yml檔案

Step1."手動"建立github資料夾

Step2."手動"建立workflows資料夾

Step3."手動"建立yml檔

Desktop View

編輯yml內容

yml檔中,若中輸入簡單的指令,Push到Github時,就能在Action看到指令的運作了

Desktop View

1
2
3
4
5
6
7
8
name: command
on: [push]
jobs:
    run-shell-command:
        runs-on: ubuntu-18.04
        steps:
            - name: echo a string
              run: echo "HI"

也可以使用cron來排程執行action

下面cron的寫法代表5分鐘執行一次,而cron的寫法參考如下網址

https://crontab.guru/examples.html

1
2
3
4
5
6
7
8
9
10
name: command
on:
    schedule:
    - cron: "0/5 * * * *" 
jobs:
    run-shell-command:
        runs-on: ubuntu-18.04
        steps:
            - name: echo a string
              run: echo "HI"

C#專案Push到Github時,自動進行單元測試

建立DEMO專案

Desktop View

建立測試專案

Desktop View Desktop View Desktop View Desktop View

輸入單元測試內容

Desktop View

本地運行單元測試

Desktop View

編輯測試專案的csproj檔

這一個步驟,是為了讓單元測試的結果,以Report的方式顯示

將其PropertyGroup屬性中,追加VSTestLogger與VSTestResultsDirectory屬性,如下

Desktop View

1
2
<VSTestLogger>trx%3bLogFileName=$(MSBuildProjectName).trx</VSTestLogger>
<VSTestResultsDirectory>$(MSBuildThisFileDirectory)/TestResults/$(TargetFramework)</VSTestResultsDirectory>

手動配置yml

Desktop View

編輯yml

yml內容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
name: CI
on: [push]
jobs:
  build_and_test:

    env:
      BUILD_CONFIG: 'Debug'
      SOLUTION: 'GithubActionDemo/GithubActionDemo.sln'

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Setup .NET
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: 6.x


    - name: Restore dependencies
      run: dotnet restore $SOLUTION

    - name: Build
      run: dotnet build $SOLUTION --configuration $BUILD_CONFIG
  
    - name: Test
      run: dotnet test $SOLUTION  --configuration $BUILD_CONFIG --logger "trx;LogFileName=test-results.trx" || true
    - name: Test Report
      uses: dorny/test-reporter@v1
      if: always()
      with:
        name: DotNET Tests
        path: "**/test-results.trx"                            
        reporter: dotnet-trx
        fail-on-error: true

Push到Github

將專案Push到Github後,然後進入Action

Desktop View

選擇最新的Commit

Desktop View

Bulid and Test是測試部署

選擇DotNet Test

Desktop View

DotNet Test中,可以看到單元測試的結果

Desktop View

重要參考

https://rakesh-suryawanshi.medium.com/unit-testing-report-with-github-actions-7216f340044e https://stackoverflow.com/questions/60126813/github-actions-report-dotnet-test-result-as-annotations https://stackoverflow.com/questions/61464151/how-it-is-possible-to-avoid-a-push-in-github-when-the-workflow-tests-fails

本文由作者按照 CC BY 4.0 進行授權