2
1

More than 3 years have passed since last update.

Visual Studio Code で編集中のテストコードを実行する (Golang編)

Last updated at Posted at 2020-04-26

TL;DR

Visual Studio Code で編集中のテストコードを実行する

 この記事にいたく感動したのでGo言語でもショートカット一発で任意の関数をテストしたくなった!

できばえ

  • 開発言語非依存にしたかったのでシェルスクリプトで実装しました
  • 関数名を定義した行に移動するのがめんどいかったのでコードの途中からでも出来るようにしました

1.png

やりかた

・以下、gotet.shをプロジェクト名フォルダの下に置いてください

gotest.sh
relativeFile=$1
lineNumber=$2
line=0
funcName=""
while :
do
 cursol=`expr $lineNumber - $line`
 if [ "$cursol" = "0" ]; then
 break
 fi

 strs=`sed -n ${cursol}p $relativeFile | grep func | grep testing.T`

 if [ "$strs" != "" ]; then
 funcName=$strs
 break
 fi

 line=`expr $line + 1`
done

if [ "$funcName" != "" ]; then
 funcName=`echo $funcName | cut -d " " -f 2 | cut -d "(" -f 1`
 echo "Testing function: $funcName"
 go test -run $funcName
else
 echo "not find Test function name..."
fi

・元記事の通りプロジェクト名フォルダの下に.vscodeを掘って、以下tasks.jsonを置く

tasks.json
{
 "version": "2.0.0",
 "tasks": [
 {
 "label": "run Go test here",
 "type": "shell",
 "command": "sh gotest.sh ${relativeFile} ${lineNumber}",
 "group": "test",
 "presentation": {
 "reveal": "always",
 "panel": "shared"
 }
 }
 ]
}

このあたりを参照にキーバインドを設定してください

tasks.json
[
 {
 "key": "ctrl+shift+a",
 "command": "workbench.action.tasks.runTask",
 "args": "run Go test here"
 }
]

ではでは

Windowsでもcygwinとかインストールすれば問題なく動きます。
Gow軽くて良いっすよ!

さらに

VS CodeのGo言語テストコード生成ツールを使ってみたらめちゃくちゃ便利だった話とか
こちらと組み合わせてテストテンプレートを自動生成するとテスト能率爆上がりなんでオススメです!!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1