Assertions Cheet sheet

Laravel Test PHPUnit Assertions Cheet sheet

String Assertions

assertStringContainsString()

$this->assertStringContainsString('foo', 'bar');

assertStringContainsStringIgnoringCase()

$this->assertStringContainsStringIgnoringCase('foo', 'bar');

assertContainsOnlyInstancesOf()

$this->assertContainsOnlyInstancesOf(
    Foo::class,
    [new Foo, new Bar, new Foo]
);

assertEqualsIgnoringCase()

$this->assertEqualsIgnoringCase('foo', 'BAR');

assertMatchesRegularExpression()

$this->assertMatchesRegularExpression('/foo/', 'bar');

assertStringMatchesFormat()

$this->assertStringMatchesFormat('%i', 'foo');
Placeholder Description
%e Represents a directory separator, for example / on Linux.
%s One or more of anything (character or white space) except the end of line character.
%S Zero or more of anything (character or white space) except the end of line character.
%a One or more of anything (character or white space) including the end of line character.
%A Zero or more of anything (character or white space) including the end of line character.
%w Zero or more white space characters.
%i A signed integer value, for example +3142, -3142.
%d An unsigned integer value, for example 123456.
%x One or more hexadecimal character. That is, characters in the range 0-9, a-f, A-F.
%f A floating point number, for example: 3.142, -3.142, 3.142E-10, 3.142e+10.
%c A single character of any sort.
%% A literal percent character: %.

assertStringEndsWith()

$this->assertStringEndsWith('suffix', 'foo');

assertStringStartsWith()

$this->assertStringStartsWith('prefix', 'foo');

JSON String Assertions

assertJsonStringEqualsJsonString()

$this->assertJsonStringEqualsJsonString(
    json_encode(['Mascot' => 'Tux']),
    json_encode(['Mascot' => 'ux'])
);

Array Assertions

assertArrayHasKey()

$this->assertArrayHasKey('foo', ['bar' => 'baz']);

assertContains()

$this->assertContains(4, [1, 2, 3]);

assertContainsOnly()

$this->assertContainsOnly('string', ['1', '2', 3]);

assertCount()

$this->assertCount(0, ['foo']);

assertEmpty()

$this->assertEmpty(['foo']);

Number Assertions

assertEqualsWithDelta()

$this->assertEqualsWithDelta(1.0, 1.5, 0.1);

assertGreaterThan()

$this->assertGreaterThan(2, 1);

assertGreaterThanOrEqual()

$this->assertGreaterThanOrEqual(2, 1);

assertInfinite()

$this->assertInfinite(1);

assertLessThan()

$this->assertLessThan(1, 2);

assertLessThanOrEqual()

$this->assertLessThanOrEqual(1, 2);

assertNan()

$this->assertNan(1);

Boolean Assertions

assertFalse()

$this->assertFalse(true);

assertTrue()

$this->assertTrue(false);

Variable Type Assertions

assertInstanceOf()

$this->assertInstanceOf(RuntimeException::class, new Exception);

assertIsArray()

$this->assertIsArray(null);

assertIsBool()

$this->assertIsBool(null);

assertIsCallable()

$this->assertIsCallable(null);

assertIsFloat()

$this->assertIsFloat(null);

assertIsInt()

$this->assertIsInt(null);

assertIsIterable()

$this->assertIsIterable(null);

assertIsNumeric()

$this->assertIsNumeric(null);

assertIsObject()

$this->assertIsObject(null);

assertIsResource()

$this->assertIsResource(null);

assertIsScalar()

$this->assertIsScalar(null);

assertIsString()

$this->assertIsString(null);

assertNull()

$this->assertNull('foo');

Class / Object Assertions

assertClassHasAttribute()

$this->assertClassHasAttribute('foo', stdClass::class);

assertClassHasStaticAttribute()

$this->assertClassHasStaticAttribute('foo', stdClass::class);

assertEquals()

$this->assertEquals(1, 0);
$this->assertEquals('bar', 'baz');
$this->assertEquals("foo\nbar\nbaz\n", "foo\nbah\nbaz\n");
$expected = new DOMDocument;
$expected->loadXML('<foo><bar/></foo>');

$actual = new DOMDocument;
$actual->loadXML('<bar><foo/></bar>');

$this->assertEquals($expected, $actual);
$expected = new stdClass;
$expected->foo = 'foo';
$expected->bar = 'bar';

$actual = new stdClass;
$actual->foo = 'bar';
$actual->baz = 'bar';

$this->assertEquals($expected, $actual);
$this->assertEquals(['a', 'b', 'c'], ['a', 'c', 'd']);

assertEqualsCanonicalizing()

$this->assertEqualsCanonicalizing([3, 2, 1], [2, 3, 0, 1]);

assertObjectEquals()

$a = new Email('user@example.org');
$b = new Email('user@example.org');
$c = new Email('user@example.com');

// This passes
$this->assertObjectEquals($a, $b);

// This fails
$this->assertObjectEquals($a, $c);
//  Email value object with equals() method
<?php declare(strict_types=1);
final class Email
{
    private string $email;

    public function __construct(string $email)
    {
        $this->ensureIsValidEmail($email);

        $this->email = $email;
    }

    public function asString(): string
    {
        return $this->email;
    }

    public function equals(self $other): bool
    {
        return $this->asString() === $other->asString();
    }

    private function ensureIsValidEmail(string $email): void
    {
        // ...
    }
}

assertObjectHasAttribute()

$this->assertObjectHasAttribute('foo', new stdClass);

assertSame()

$this->assertSame('2204', 2204);
$this->assertSame(new stdClass, new stdClass);

assertSameSize()

$this->assertSameSize([1, 2], [1]);

assertThat()

$theBiscuit = new Biscuit('Ginger');
$myBiscuit  = new Biscuit('Ginger');

$this->assertThat(
    $theBiscuit,
    $this->logicalNot(
        $this->equalTo($myBiscuit)
    )
);
Constraint Description
PHPUnit\Framework\Constraint\IsAnything anything() Constraint that accepts any input value.
PHPUnit\Framework\Constraint\ArrayHasKey arrayHasKey(mixed $key) Constraint that asserts that the array has a given key.
PHPUnit\Framework\Constraint\TraversableContains contains(mixed $value) Constraint that asserts that the array or object that implements the Iterator interface contains a given value.
PHPUnit\Framework\Constraint\TraversableContainsOnly containsOnly(string $type) Constraint that asserts that the array or object that implements the Iterator interface contains only values of a given type.
PHPUnit\Framework\Constraint\TraversableContainsOnly containsOnlyInstancesOf(string $classname) Constraint that asserts that the array or object that implements the Iterator interface contains only instances of a given classname.
PHPUnit\Framework\Constraint\IsEqual equalTo($value, $delta = 0, $maxDepth = 10) Constraint that checks if one value is equal to another.
PHPUnit\Framework\Constraint\DirectoryExists directoryExists() Constraint that checks if the directory exists.
PHPUnit\Framework\Constraint\FileExists fileExists() Constraint that checks if the file(name) exists.
PHPUnit\Framework\Constraint\IsReadable isReadable() Constraint that checks if the file(name) is readable.
PHPUnit\Framework\Constraint\IsWritable isWritable() Constraint that checks if the file(name) is writable.
PHPUnit\Framework\Constraint\GreaterThan greaterThan(mixed $value) Constraint that asserts that the value is greater than a given value.
PHPUnit\Framework\Constraint\LogicalOr greaterThanOrEqual(mixed $value) Constraint that asserts that the value is greater than or equal to a given value.
PHPUnit\Framework\Constraint\ClassHasAttribute classHasAttribute(string $attributeName) Constraint that asserts that the class has a given attribute.
PHPUnit\Framework\Constraint\ClassHasStaticAttribute classHasStaticAttribute(string $attributeName) Constraint that asserts that the class has a given static attribute.
PHPUnit\Framework\Constraint\ObjectHasAttribute objectHasAttribute(string $attributeName) Constraint that asserts that the object has a given attribute.
PHPUnit\Framework\Constraint\IsIdentical identicalTo(mixed $value) Constraint that asserts that one value is identical to another.
PHPUnit\Framework\Constraint\IsFalse isFalse() Constraint that asserts that the value is false.
PHPUnit\Framework\Constraint\IsInstanceOf isInstanceOf(string $className) Constraint that asserts that the object is an instance of a given class.
PHPUnit\Framework\Constraint\IsNull isNull() Constraint that asserts that the value is null.
PHPUnit\Framework\Constraint\IsTrue isTrue() Constraint that asserts that the value is true.
PHPUnit\Framework\Constraint\IsType isType(string $type) Constraint that asserts that the value is of a specified type.
PHPUnit\Framework\Constraint\LessThan lessThan(mixed $value) Constraint that asserts that the value is smaller than a given value.
PHPUnit\Framework\Constraint\LogicalOr lessThanOrEqual(mixed $value) Constraint that asserts that the value is smaller than or equal to a given value.
logicalAnd() Logical AND.
logicalNot(PHPUnit\Framework\Constraint $constraint) Logical NOT.
logicalOr() Logical OR.
logicalXor() Logical XOR.
PHPUnit\Framework\Constraint\PCREMatch matchesRegularExpression(string $pattern) Constraint that asserts that the string matches a regular expression.
PHPUnit\Framework\Constraint\StringContains stringContains(string $string, bool $case) Constraint that asserts that the string contains a given string.
PHPUnit\Framework\Constraint\StringEndsWith stringEndsWith(string $suffix) Constraint that asserts that the string ends with a given suffix.
PHPUnit\Framework\Constraint\StringStartsWith stringStartsWith(string $prefix) Constraint that asserts that the string starts with a given prefix.

File / Directory Assertions

assertDirectoryExists()

$this->assertDirectoryExists('/path/to/directory');

assertDirectoryIsReadable()

$this->assertDirectoryIsReadable('/path/to/directory');

assertDirectoryIsWritable()

$this->assertDirectoryIsWritable('/path/to/directory');

assertFileEquals()

$this->assertFileEquals('/home/sb/expected', '/home/sb/actual');

assertFileExists()

$this->assertFileExists('/path/to/file');

assertFileIsReadable()

$this->assertFileIsReadable('/path/to/file');

assertFileIsWritable()

$this->assertFileIsWritable('/path/to/file');

assertIsReadable()

$this->assertIsReadable('/path/to/unreadable');

assertIsWritable()

$this->assertIsWritable('/path/to/unwritable');

assertJsonFileEqualsJsonFile()

$this->assertJsonFileEqualsJsonFile('path/to/fixture/file', 'path/to/actual/file');

assertJsonStringEqualsJsonFile()

$this->assertJsonStringEqualsJsonFile('path/to/fixture/file', json_encode(['Mascot' => 'ux']));

assertStringMatchesFormatFile()

$this->assertStringMatchesFormatFile('/path/to/expected.txt', 'foo');

assertStringEqualsFile()

$this->assertStringEqualsFile('/home/sb/expected', 'actual');

assertXmlFileEqualsXmlFile()

$this->assertXmlFileEqualsXmlFile('/home/sb/expected.xml', '/home/sb/actual.xml');

assertXmlStringEqualsXmlFile()

$this->assertXmlStringEqualsXmlFile('/home/sb/expected.xml', '<foo><baz/></foo>');

assertXmlStringEqualsXmlString()

$this->assertXmlStringEqualsXmlString('<foo><bar/></foo>', '<foo><baz/></foo>');

Reference