LoginSignup
50
51

More than 5 years have passed since last update.

composer で入れた phpunit で少し楽をする

Last updated at Posted at 2013-07-16

最近は phpunit も composer で入れるのが流行っているらしいです。

Before

composer で phpunit を入れると(標準では)vendor/bin/phpunit に置かれるので次のように実行します。

$ vendor/bin/phpunit

テストが置いているディレクトリは phpunit.xml.dist や phpunit.xml に記述しているのでこれだけで OK です。

最近はプロジェクトルートに置くファイルが多くなってきたので phpunit.xml はプロジェクト直下ではなく tests/ ディレクトリに置くのがマイブームです。

なので次のようになります。

$ vendor/bin/phpunit -c tests/

特定のテストだけ実行したいこともあります。その場合は次のようになります。

$ vendor/bin/phpunit -c tests/ tests/Foo/Bar/BazTest.php

ディレクトリを指定することも出来るので、特定のディレクトリのテストを全部実行したければ次のようになります。

$ vendor/bin/phpunit -c tests/ tests/Foo/Bar/

特定のディレクトリのテストだけ何度も実行するならそのディレクトリに cd しておいてもいいかもしれません。

$ cd tests/Foo/Bar/
$ ../../../vendor/bin/phpunit -c ../../../tests/ .

テストが捗り・・・ます??

After

composer で phpunit を入れると(標準では)vendor/bin/phpunit に置かれますが次のように実行します。

$ phpunit

テストが置いているディレクトリは phpunit.xml.dist や phpunit.xml に記述しているのでこれだけで OK です。

最近はプロジェクトルートに置くファイルが多くなってきたので phpunit.xml はプロジェクト直下ではなく tests/ ディレクトリに置くのがマイブームです。

それでも次のようになります。

$ phpunit

特定のテストだけ実行したいこともあります。その場合は次のようになります。

$ phpunit tests/Foo/Bar/Baz.php

ディレクトリを指定することも出来るので、特定のディレクトリのテストを全部実行したければ次のようになります。

$ phpunit tests/Foo/Bar/

特定のディレクトリのテストだけ何度も実行するならそのディレクトリに cd しておいてもいいかもしれません。

$ cd tests/Foo/Bar/
$ phpunit .

テストが捗ります。

Answer

次のようなシェル関数を定義しています。

function phpunit
{
    local root="${PWD}"

    while [ -n "${root}" ]; do
        if [ -x "${root}/vendor/bin/phpunit" ]; then
            break
        fi
        root="${root%/*}"
    done

    if [ -z "${root}" ]; then
        command phpunit "$@"
        return $?
    fi

    local cmd=("${root}/vendor/bin/phpunit")

    local dir xml

    for dir in "/tests/" "/" ; do
        for xml in "phpunit.xml.dist" "phpunit.xml"; do
            if [ -e "${root}${dir}${xml}" ]; then
                cmd=("${cmd[@]}" "--configuration=${root}${dir}")
                break 2
            fi
        done
    done

    cmd=("${cmd[@]}" "--colors")

    "${cmd[@]}" "$@" | cat
    return ${PIPESTATUS[0]}
}

カレントディレクトリから遡って vendor/bin/phpunit を探して見つかればそれを実行。
なければ PATH の通った phpunit コマンドを実行します。

vendor/bin/phpunit が見つかったときは次の順番でファイルを探し、見つかったらそのディレクトリを --configuration で指定します。

  • tests/phpunit.xml.dist
  • tests/phpunit.xml
  • phpunit.xml.dist
  • phpunit.xml

ついでに色付けのために --colors も追加します(phpunit.xml には書かないポリシー)。

最後の |cat は msysgit で色付けするためのオマジナイです。

50
51
3

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
50
51