I’ve come across a few things whilst using phpunit which has made my development life a bit easier whilst writing tests. Here are a list of a few:

Running a single test file

It’s possible run a single test file by just adding the filepath as the final argument:

phpunit tests/Unit/ModelTest.php

Filtering tests

I learnt early on that you are able to filter tests based on the file name. A quick example would be:

phpunit --filter=Example

phpunit will only run a test whih has Example in its file name. This also means you can run a single test by doing the following:

phpunit --filter=ModelTest

You can also run one individual test using this:

phpunit --filter=testTrueDoesNotEqualFalse

Grouping tests

I recently was working with a test file which had around 20+ tests. Issue with this is, if I am aiming to see the results of just a few of these tests, I would run the all tests in the file using phpunit --filter=ExampleTest.

What I found was using the @group tag helped me to single out just the tests I wanted to see the current status of.

/**
* Test to see that my code is working.
*
* @group target
*/
public function test_that_my_code_is_working()
{
    // ...
}

target can be renamed to anything that you would like. Now running your phpunit suite based on a group is done with the following command:

phpunit --group=target

This helps if you have several tests in different files that you want to make sure is working.

Using the @test tag

If you ever get fed up of using test_ as the start of your test function names, you can simply add the @test tag. This will let phpunit know that this is a text regardless of its function name:

/**
* Test to see that my code is working.
*
* @test
*/
public function my_code_is_working()
{
    // ...
}

Stop on failure

If you want running tests after the first failed tests, use the following:

phpunit --stop-on-failure

Asserting count

When using laravel eloquent models, I initially defaulted to ->assertEquals() when checking whether or not there were a certain amount of records in my database.

$this->assertEquals(5, Model::count());

This is fine, however if you end up checking the count of a relationship, it will take a ->count() to return the correct value:

$this->assertEquals(5, User::find(1)->posts()->count());

Using ->assertCount() will count any iterable value you pass to it:

$this->assertCount(5, User::find(1)->posts);

This is handy as you wont need to run a separate count method if store your model into its own variable for another test.