Phpunit测试发出警告没有在课堂上发现的测试

问题描述 投票:40回答:4

我正在尝试学习如何使用phpunit和laravel进行测试。使用phpunit命令启动测试时,我收到警告:

There was 1 failure:

1) Warning
No tests found in class "PostsTest".

FAILURES!                            
Tests: 2, Assertions: 1, Failures: 

我的测试类名和文件名匹配。我已经阅读了有关不匹配名称的其他问题。我的文件名是PostsTest.php和我的测试文件:

class PostsTest extends ApiTester {


    public function it_fetches_posts()

    {
        $this->times(5)->makePost();

        $this->getJson('api/v1/posts');

        $this->assertResponseOk();

    }

    private function makePost($postFields=[])
    {
        $post = array_merge([
            'title' => $this->fake->sentence,
            'content' => $this->fake->paragragraph
        ], $postFields);

        while($this->times --)Post::create($post);
    }
}

如果有必要,我的ApiTester:

use Faker\Factory as Faker;

class ApiTester extends TestCase {
    protected $fake;
    protected $times = 1;
    function __construct($faker)
    {
        $this->fake = Faker::create();
    }
}

我不知道错误在哪里。 Laravel或我当地的phpunit设置或其他任何东西。任何帮助表示赞赏。

谢谢。

php laravel phpunit
4个回答
65
投票

Annotations are the answer

/** @test */
public function it_tests_something()
{
  ...
}

添加@test告诉phpunit将该函数视为测试,无论名称如何。


88
投票

PHPUnit将识别为测试的唯一方法是名称为starting with test的方法。

所以你应该将it_fetches_posts()方法重命名为test_it_fetches_poststestItFetchesPosts。驼峰案例命名是可选的,但如果稍后使用--testdox选项则很有用。

另外,如其他答案中所述,您还可以将@test注释添加到任何方法,它将被视为PHPUnit的测试。


2
投票

要么像test_something_should_work这样的单词'test'开始它的名字,要么用这个注释/** @test */更新测试文档


0
投票

另外,考虑一个你正在测试需要类A(你会模拟)的类B的情况。当调用$a->someMethod($mocked_B_class)时,请确保您没有任何警告,例如尝试访问数组的属性,就像访问类($array = ['one','two']; $array->one)的属性一样。

在这种情况下,它不会给你任何有关测试或错误的信息

© www.soinside.com 2019 - 2024. All rights reserved.