PHPUnit の実行時に ArgumentCountError が発生した意外な理由

PHPUnit でユニットテストを実行した際に、以下のエラーが発生して試行錯誤して意外な原因にたどり着いたのでメモしておく。

1
ArgumentCountError: Too few arguments to function Tests\SampleTesst::test_showMessage(), 0 passed in /root/vendor/phpunit/phpunit/src/Framework/TestCase.php on line 1415 and exactly 1 expected

まず、以下のようなテストコードを作成した。

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
<?php
declare(strict_types=1);

namespace Tests;

use PHPUnit;

require_once dirname(__FILE__).'/../vendor/autoload.php';

class SampleTesst extends PHPUnit\Framework\TestCase
{
/*
* @dataProvider provider_showMessage
* @param string $message
*/
public function test_showMessage(string $message): void
{
$this->assertEquals('Hello', $message);
}

public function provider_showMessage()
{
return [
'OK' => ['Hello'],
];
}
}

一見すると特に問題なく動くような気がするが、実際にテストを実行してみると、エラーになってしまう。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# vendor/bin/phpunit tests/SampleTesst.php
PHPUnit 8.5.13 by Sebastian Bergmann and contributors.

E 1 / 1 (100%)

Time: 28 ms, Memory: 4.00 MB

There was 1 error:

1) Tests\SampleTesst::test_showMessage
ArgumentCountError: Too few arguments to function Tests\SampleTesst::test_showMessage(), 0 passed in /root/vendor/phpunit/phpunit/src/Framework/TestCase.php on line 1415 and exactly 1 expected

/root/tests/SampleTesst.php:16

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

色々、試行錯誤を繰り返した結果、エラーが発生しなくなったてーすコードがこちら。

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
<?php
declare(strict_types=1);

namespace Tests;

use PHPUnit;

require_once dirname(__FILE__).'/../vendor/autoload.php';

class SampleTesst extends PHPUnit\Framework\TestCase
{
/*
* @dataProvider provider_showMessage
* @param string $message
*/
public function test_showMessage(string $message): void
{
$this->assertEquals('Hello', $message);
}

public function provider_showMessage()
{
return [
'OK' => ['Hello'],
];
}
}

テストを実行すると、問題なく OK となる。

1
2
3
4
5
6
7
8
# vendor/bin/phpunit tests/SampleTesst.php
PHPUnit 8.5.13 by Sebastian Bergmann and contributors.

. 1 / 1 (100%)

Time: 31 ms, Memory: 4.00 MB

OK (1 test, 1 assertion)

修正前のテストコードと修正後のテストコードの diff をとってみる。

1
2
3
4
5
6
7
8
9
10
11
12
# diff tests/before_SampleTesst.php tests/after_SampleTesst.php
--- tests/before_SampleTesst.php
+++ tests/after_SampleTesst.php
@@ -9,7 +9,7 @@

class SampleTesst extends PHPUnit\Framework\TestCase
{
- /**
+ /*
* @dataProvider provider_showMessage
* @param string $message
*/

‘/‘ と ‘/*‘ が成否を分けていた。

あらためて PHPUnit のドキュメント を読んでみると、確かに ‘/**’ を使えと書いてあった。

PHP の doc コメントは、/** で始めて */ で終わる必要があります。 その他の形式のコメントで書いたアノテーションは、無視されます。

普段は ‘/*’ を使っているが、なぜかここだけ ‘/‘ を使っていたので発生したミスだった。