Apêndice A. Asserções

Esse apêndice lista os vários métodos de asserções que estão disponíveis.

Uso Estático vs. Não-Estático de Métodos de Asserção

Asserções do PHPUnit são implementadas in PHPUnit\Framework\Assert. PHPUnit\Framework\TestCase herda de PHPUnit\Framework\Assert.

Os métodos de asserção são declarados static e podem ser invocados de qualquer contexto usando PHPUnit\Framework\Assert::assertTrue(), por exemplo, ou usando $this->assertTrue() ou self::assertTrue(), por exemplo, em uma classe que extende PHPUnit\Framework\TestCase.

Na verdade, você pode usar invólucros de funções globais tal como assertTrue() em qualquer contexto (incluindo classes que extendem PHPUnit\Framework\TestCase) quando você (manualmente) inclui o arquivo de código-fonte src/Framework/Assert/Functions.php que vem com PHPUnit.

Uma questão comum, especialmente de desenvolvedores novos em PHPUnit, é se usar $this->assertTrue() ou self::assertTrue(), por exemplo, é "a forma certa" de invocar uma asserção. A resposta rápida é: não existe forma certa. E também não existe forma errada. Isso é mais uma questão de preferência.

Para a maioria das pessoas "se sente melhor" usar $this->assertTrue() porque o método de teste é invocado em um objeto de teste. O fato de que os métodos de asserção são declarados static permite (re)usá-los de fora do escopo de um objeto de teste. Por último, os invólucros de funções globais permitem desenvolvedores digitarem menos caracteres (assertTrue() ao invés de $this->assertTrue() ou self::assertTrue()).

assertArrayHasKey()

assertArrayHasKey(mixed $key, array $array[, string $message = ''])

Reporta um erro identificado pela $message se o $array não contém a $key.

assertArrayNotHasKey() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.1: Utilização de assertArrayHasKey()

<?php
use PHPUnit\Framework\TestCase;

class ArrayHasKeyTest extends TestCase
{
    public function testFailure()
    {
        $this->assertArrayHasKey('foo', ['bar' => 'baz']);
    }
}
?>
phpunit ArrayHasKeyTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ArrayHasKeyTest::testFailure
Failed asserting that an array has the key 'foo'.

/home/sb/ArrayHasKeyTest.php:6

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


assertClassHasAttribute()

assertClassHasAttribute(string $attributeName, string $className[, string $message = ''])

Reporta um erro identificado pela $message se $className::attributeName não existir.

assertClassNotHasAttribute() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.2: Utilização de assertClassHasAttribute()

<?php
use PHPUnit\Framework\TestCase;

class ClassHasAttributeTest extends TestCase
{
    public function testFailure()
    {
        $this->assertClassHasAttribute('foo', stdClass::class);
    }
}
?>
phpunit ClassHasAttributeTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) ClassHasAttributeTest::testFailure
Failed asserting that class "stdClass" has attribute "foo".

/home/sb/ClassHasAttributeTest.php:6

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


assertArraySubset()

assertArraySubset(array $subset, array $array[, bool $strict = '', string $message = ''])

Reporta um erro identificado pela $message se $array não contém o $subset.

$strict é uma flag usada para comparar a identidade de objetos dentro dos arrays.

Exemplo A.3: Utilização de assertArraySubset()

<?php
use PHPUnit\Framework\TestCase;

class ArraySubsetTest extends TestCase
{
    public function testFailure()
    {
        $this->assertArraySubset(['config' => ['key-a', 'key-b']], ['config' => ['key-a']]);
    }
}
?>
phpunit ArrayHasKeyTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) Epilog\EpilogTest::testNoFollowOption
Failed asserting that an array has the subset Array &0 (
    'config' => Array &1 (
        0 => 'key-a'
        1 => 'key-b'
    )
).

/home/sb/ArraySubsetTest.php:6

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


assertClassHasStaticAttribute()

assertClassHasStaticAttribute(string $attributeName, string $className[, string $message = ''])

Reporta um erro identificado pela $message se o $className::attributeName não existir.

assertClassNotHasStaticAttribute() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.4: Utilização de assertClassHasStaticAttribute()

<?php
use PHPUnit\Framework\TestCase;

class ClassHasStaticAttributeTest extends TestCase
{
    public function testFailure()
    {
        $this->assertClassHasStaticAttribute('foo', stdClass::class);
    }
}
?>
phpunit ClassHasStaticAttributeTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) ClassHasStaticAttributeTest::testFailure
Failed asserting that class "stdClass" has static attribute "foo".

/home/sb/ClassHasStaticAttributeTest.php:6

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


assertContains()

assertContains(mixed $needle, Iterator|array $haystack[, string $message = ''])

Reporta um erro identificado pela $message se o $needle não é um elemento de $haystack.

assertNotContains() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeContains() e assertAttributeNotContains() são invólucros convenientes que usam um atributo public, protected, ou private de uma classe ou objeto como a haystack.

Exemplo A.5: Utilização de assertContains()

<?php
use PHPUnit\Framework\TestCase;

class ContainsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertContains(4, [1, 2, 3]);
    }
}
?>
phpunit ContainsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ContainsTest::testFailure
Failed asserting that an array contains 4.

/home/sb/ContainsTest.php:6

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


assertContains(string $needle, string $haystack[, string $message = '', boolean $ignoreCase = FALSE])

Reporta um erro identificado pela $message se $needle não é uma substring de $haystack.

Se $ignoreCase é true, o teste irá ser case insensitive.

Exemplo A.6: Utilização de assertContains()

<?php
use PHPUnit\Framework\TestCase;

class ContainsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertContains('baz', 'foobar');
    }
}
?>
phpunit ContainsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ContainsTest::testFailure
Failed asserting that 'foobar' contains "baz".

/home/sb/ContainsTest.php:6

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


Exemplo A.7: Utilização de assertContains() com $ignoreCase

<?php
use PHPUnit\Framework\TestCase;

class ContainsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertContains('foo', 'FooBar');
    }

    public function testOK()
    {
        $this->assertContains('foo', 'FooBar', '', true);
    }
}
?>
phpunit ContainsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F.

Time: 0 seconds, Memory: 2.75Mb

There was 1 failure:

1) ContainsTest::testFailure
Failed asserting that 'FooBar' contains "foo".

/home/sb/ContainsTest.php:6

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


assertContainsOnly()

assertContainsOnly(string $type, Iterator|array $haystack[, boolean $isNativeType = null, string $message = ''])

Reporta um erro identificado pela $message se $haystack não contém somente variáveis do tipo $type.

$isNativeType é uma flag usada para indicar se $type é um tipo nativo do PHP ou não.

assertNotContainsOnly() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeContainsOnly() e assertAttributeNotContainsOnly() são invólucros convenientes que usam um atributo public, protected, ou private de uma classe ou objeto como a haystack.

Exemplo A.8: Utilização de assertContainsOnly()

<?php
use PHPUnit\Framework\TestCase;

class ContainsOnlyTest extends TestCase
{
    public function testFailure()
    {
        $this->assertContainsOnly('string', ['1', '2', 3]);
    }
}
?>
phpunit ContainsOnlyTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ContainsOnlyTest::testFailure
Failed asserting that Array (
    0 => '1'
    1 => '2'
    2 => 3
) contains only values of type "string".

/home/sb/ContainsOnlyTest.php:6

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


assertContainsOnlyInstancesOf()

assertContainsOnlyInstancesOf(string $classname, Traversable|array $haystack[, string $message = ''])

Reporta um erro identificado pela $message se $haystack não contém somente instâncias da classe $classname.

Exemplo A.9: Utilização de assertContainsOnlyInstancesOf()

<?php
use PHPUnit\Framework\TestCase;

class ContainsOnlyInstancesOfTest extends TestCase
{
    public function testFailure()
    {
        $this->assertContainsOnlyInstancesOf(
            Foo::class,
            [new Foo, new Bar, new Foo]
        );
    }
}
?>
phpunit ContainsOnlyInstancesOfTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ContainsOnlyInstancesOfTest::testFailure
Failed asserting that Array ([0]=> Bar Object(...)) is an instance of class "Foo".

/home/sb/ContainsOnlyInstancesOfTest.php:6

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


assertCount()

assertCount($expectedCount, $haystack[, string $message = ''])

Reporta um erro identificado pela $message se o número de elementos no $haystack não for $expectedCount.

assertNotCount() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.10: Utilização de assertCount()

<?php
use PHPUnit\Framework\TestCase;

class CountTest extends TestCase
{
    public function testFailure()
    {
        $this->assertCount(0, ['foo']);
    }
}
?>
phpunit CountTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) CountTest::testFailure
Failed asserting that actual size 1 matches expected size 0.

/home/sb/CountTest.php:6

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


assertDirectoryExists()

assertDirectoryExists(string $directory[, string $message = ''])

Reporta um erro identificado pela $message se o diretório especificado por $directory não existir.

assertDirectoryNotExists() é o inverso dessa asserção e recebe os mesmos argumentos.

Exemplo A.11: Utilização de assertDirectoryExists()

<?php
use PHPUnit\Framework\TestCase;

class DirectoryExistsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertDirectoryExists('/path/to/directory');
    }
}
?>
phpunit DirectoryExistsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) DirectoryExistsTest::testFailure
Failed asserting that directory "/path/to/directory" exists.

/home/sb/DirectoryExistsTest.php:6

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


assertDirectoryIsReadable()

assertDirectoryIsReadable(string $directory[, string $message = ''])

Reporta um erro identificado pela $message se o diretório especificado por $directory não é um diretório ou não é legível.

assertDirectoryNotIsReadable() é o inverso dessa asserção e recebe os mesmos argumentos.

Exemplo A.12: Utilização de assertDirectoryIsReadable()

<?php
use PHPUnit\Framework\TestCase;

class DirectoryIsReadableTest extends TestCase
{
    public function testFailure()
    {
        $this->assertDirectoryIsReadable('/path/to/directory');
    }
}
?>
phpunit DirectoryIsReadableTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) DirectoryIsReadableTest::testFailure
Failed asserting that "/path/to/directory" is readable.

/home/sb/DirectoryIsReadableTest.php:6

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


assertDirectoryIsWritable()

assertDirectoryIsWritable(string $directory[, string $message = ''])

Reporta um erro identificado pela $message se o diretório especificado por $directory não é um diretório ou não é gravável.

assertDirectoryNotIsWritable() é o inverso dessa asserção e recebe os mesmos argumentos.

Exemplo A.13: Utilização de assertDirectoryIsWritable()

<?php
use PHPUnit\Framework\TestCase;

class DirectoryIsWritableTest extends TestCase
{
    public function testFailure()
    {
        $this->assertDirectoryIsWritable('/path/to/directory');
    }
}
?>
phpunit DirectoryIsWritableTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) DirectoryIsWritableTest::testFailure
Failed asserting that "/path/to/directory" is writable.

/home/sb/DirectoryIsWritableTest.php:6

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


assertEmpty()

assertEmpty(mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se $actual não está vazio.

assertNotEmpty() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeEmpty() e assertAttributeNotEmpty() são invólucros convenientes que podem ser aplicados para um atributo public, protected, ou private de uma classe ou objeto.

Exemplo A.14: Utilização de assertEmpty()

<?php
use PHPUnit\Framework\TestCase;

class EmptyTest extends TestCase
{
    public function testFailure()
    {
        $this->assertEmpty(['foo']);
    }
}
?>
phpunit EmptyTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) EmptyTest::testFailure
Failed asserting that an array is empty.

/home/sb/EmptyTest.php:6

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


assertEqualXMLStructure()

assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement[, boolean $checkAttributes = false, string $message = ''])

Reporta um erro identificado pela $message se a estrutura XML do DOMElement no $actualElement não é igual a estrutura XML do DOMElement no $expectedElement.

Exemplo A.15: Utilização de assertEqualXMLStructure()

<?php
use PHPUnit\Framework\TestCase;

class EqualXMLStructureTest extends TestCase
{
    public function testFailureWithDifferentNodeNames()
    {
        $expected = new DOMElement('foo');
        $actual = new DOMElement('bar');

        $this->assertEqualXMLStructure($expected, $actual);
    }

    public function testFailureWithDifferentNodeAttributes()
    {
        $expected = new DOMDocument;
        $expected->loadXML('<foo bar="true" />');

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

        $this->assertEqualXMLStructure(
          $expected->firstChild, $actual->firstChild, true
        );
    }

    public function testFailureWithDifferentChildrenCount()
    {
        $expected = new DOMDocument;
        $expected->loadXML('<foo><bar/><bar/><bar/></foo>');

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

        $this->assertEqualXMLStructure(
          $expected->firstChild, $actual->firstChild
        );
    }

    public function testFailureWithDifferentChildren()
    {
        $expected = new DOMDocument;
        $expected->loadXML('<foo><bar/><bar/><bar/></foo>');

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

        $this->assertEqualXMLStructure(
          $expected->firstChild, $actual->firstChild
        );
    }
}
?>
phpunit EqualXMLStructureTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

FFFF

Time: 0 seconds, Memory: 5.75Mb

There were 4 failures:

1) EqualXMLStructureTest::testFailureWithDifferentNodeNames
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'foo'
+'bar'

/home/sb/EqualXMLStructureTest.php:9

2) EqualXMLStructureTest::testFailureWithDifferentNodeAttributes
Number of attributes on node "foo" does not match
Failed asserting that 0 matches expected 1.

/home/sb/EqualXMLStructureTest.php:22

3) EqualXMLStructureTest::testFailureWithDifferentChildrenCount
Number of child nodes of "foo" differs
Failed asserting that 1 matches expected 3.

/home/sb/EqualXMLStructureTest.php:35

4) EqualXMLStructureTest::testFailureWithDifferentChildren
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'bar'
+'baz'

/home/sb/EqualXMLStructureTest.php:48

FAILURES!
Tests: 4, Assertions: 8, Failures: 4.


assertEquals()

assertEquals(mixed $expected, mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se as variáveis $expected e $actual não são iguais.

assertNotEquals() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeEquals() e assertAttributeNotEquals() são invólucros convenientes que usam um atributo public, protected, ou private de uma classe ou objeto como o valor atual.

Exemplo A.16: Utilização de assertEquals()

<?php
use PHPUnit\Framework\TestCase;

class EqualsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertEquals(1, 0);
    }

    public function testFailure2()
    {
        $this->assertEquals('bar', 'baz');
    }

    public function testFailure3()
    {
        $this->assertEquals("foo\nbar\nbaz\n", "foo\nbah\nbaz\n");
    }
}
?>
phpunit EqualsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

FFF

Time: 0 seconds, Memory: 5.25Mb

There were 3 failures:

1) EqualsTest::testFailure
Failed asserting that 0 matches expected 1.

/home/sb/EqualsTest.php:6

2) EqualsTest::testFailure2
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'bar'
+'baz'

/home/sb/EqualsTest.php:11

3) EqualsTest::testFailure3
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
 'foo
-bar
+bah
 baz
 '

/home/sb/EqualsTest.php:16

FAILURES!
Tests: 3, Assertions: 3, Failures: 3.


Comparações mais especializadas são usadas para tipos de argumentos específicos para $expected e $actual, veja abaixo.

assertEquals(float $expected, float $actual[, string $message = '', float $delta = 0])

Reporta um erro identificado pela $message se os dois floats $expected e $actual não estão dentro do $delta um do outro.

Por favor, leia "O Que Cada Cientista da Computação Deve Saber Sobre Aritmética de Ponto Flutuante" para entender por que $delta é necessário.

Exemplo A.17: Utilização de assertEquals() with floats

<?php
use PHPUnit\Framework\TestCase;

class EqualsTest extends TestCase
{
    public function testSuccess()
    {
        $this->assertEquals(1.0, 1.1, '', 0.2);
    }

    public function testFailure()
    {
        $this->assertEquals(1.0, 1.1);
    }
}
?>
phpunit EqualsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

.F

Time: 0 seconds, Memory: 5.75Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that 1.1 matches expected 1.0.

/home/sb/EqualsTest.php:11

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


assertEquals(DOMDocument $expected, DOMDocument $actual[, string $message = ''])

Reporta um erro identificado pela $message se a forma canonical não-comentada dos documentos XML representada pelos objetos DOMDocument $expected e $actual não são iguais.

Exemplo A.18: Utilização de assertEquals() com objetos DOMDocument

<?php
use PHPUnit\Framework\TestCase;

class EqualsTest extends TestCase
{
    public function testFailure()
    {
        $expected = new DOMDocument;
        $expected->loadXML('<foo><bar/></foo>');

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

        $this->assertEquals($expected, $actual);
    }
}
?>
phpunit EqualsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that two DOM documents are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
-<foo>
-  <bar/>
-</foo>
+<bar>
+  <foo/>
+</bar>

/home/sb/EqualsTest.php:12

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


assertEquals(object $expected, object $actual[, string $message = ''])

Reporta um erro identificado pela $message se os objetos $expected e $actual não tem valores de atributos iguais.

Exemplo A.19: Utilização de assertEquals() com objetos

<?php
use PHPUnit\Framework\TestCase;

class EqualsTest extends TestCase
{
    public function testFailure()
    {
        $expected = new stdClass;
        $expected->foo = 'foo';
        $expected->bar = 'bar';

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

        $this->assertEquals($expected, $actual);
    }
}
?>
phpunit EqualsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
 stdClass Object (
-    'foo' => 'foo'
-    'bar' => 'bar'
+    'foo' => 'bar'
+    'baz' => 'bar'
 )

/home/sb/EqualsTest.php:14

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


assertEquals(array $expected, array $actual[, string $message = ''])

Reporta um erro identificado pela $message se os arrays $expected e $actual não são iguais.

Exemplo A.20: Utilização de assertEquals() com arrays

<?php
use PHPUnit\Framework\TestCase;

class EqualsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertEquals(['a', 'b', 'c'], ['a', 'c', 'd']);
    }
}
?>
phpunit EqualsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array (
     0 => 'a'
-    1 => 'b'
-    2 => 'c'
+    1 => 'c'
+    2 => 'd'
 )

/home/sb/EqualsTest.php:6

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


assertFalse()

assertFalse(bool $condition[, string $message = ''])

Reporta um erro identificado pela $message se a $condition é true.

assertNotFalse() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.21: Utilização de assertFalse()

<?php
use PHPUnit\Framework\TestCase;

class FalseTest extends TestCase
{
    public function testFailure()
    {
        $this->assertFalse(true);
    }
}
?>
phpunit FalseTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) FalseTest::testFailure
Failed asserting that true is false.

/home/sb/FalseTest.php:6

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


assertFileEquals()

assertFileEquals(string $expected, string $actual[, string $message = ''])

Reporta um erro identificado pela $message se o arquivo especificado pelo $expected não tem o mesmo conteúdo que o arquivo especificado pelo $actual.

assertFileNotEquals() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.22: Utilização de assertFileEquals()

<?php
use PHPUnit\Framework\TestCase;

class FileEqualsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertFileEquals('/home/sb/expected', '/home/sb/actual');
    }
}
?>
phpunit FileEqualsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) FileEqualsTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'expected
+'actual
 '

/home/sb/FileEqualsTest.php:6

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.


assertFileExists()

assertFileExists(string $filename[, string $message = ''])

Reporta um erro identificado pela $message se o arquivo especificado pelo $filename não existir.

assertFileNotExists() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.23: Utilização de assertFileExists()

<?php
use PHPUnit\Framework\TestCase;

class FileExistsTest extends TestCase
{
    public function testFailure()
    {
        $this->assertFileExists('/path/to/file');
    }
}
?>
phpunit FileExistsTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) FileExistsTest::testFailure
Failed asserting that file "/path/to/file" exists.

/home/sb/FileExistsTest.php:6

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


assertFileIsReadable()

assertFileIsReadable(string $filename[, string $message = ''])

Reporta um erro identificado pela $message se o arquivo especificado por $filename não é um arquivo ou não é legível.

assertFileNotIsReadable() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.24: Usage of assertFileIsReadable()

<?php
use PHPUnit\Framework\TestCase;

class FileIsReadableTest extends TestCase
{
    public function testFailure()
    {
        $this->assertFileIsReadable('/path/to/file');
    }
}
?>
phpunit FileIsReadableTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) FileIsReadableTest::testFailure
Failed asserting that "/path/to/file" is readable.

/home/sb/FileIsReadableTest.php:6

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


assertFileIsWritable()

assertFileIsWritable(string $filename[, string $message = ''])

Reporta um erro identificado pela $message se o arquivo especificado por $filename não é um arquivo ou não é gravável.

assertFileNotIsWritable() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.25: Usage of assertFileIsWritable()

<?php
use PHPUnit\Framework\TestCase;

class FileIsWritableTest extends TestCase
{
    public function testFailure()
    {
        $this->assertFileIsWritable('/path/to/file');
    }
}
?>
phpunit FileIsWritableTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) FileIsWritableTest::testFailure
Failed asserting that "/path/to/file" is writable.

/home/sb/FileIsWritableTest.php:6

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


assertGreaterThan()

assertGreaterThan(mixed $expected, mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actual não é maior que o valor de $expected.

assertAttributeGreaterThan() é um invólucro conveniente que usa um atributo public, protected, ou private de uma classe ou objeto como o valor atual.

Exemplo A.26: Utilização de assertGreaterThan()

<?php
use PHPUnit\Framework\TestCase;

class GreaterThanTest extends TestCase
{
    public function testFailure()
    {
        $this->assertGreaterThan(2, 1);
    }
}
?>
phpunit GreaterThanTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) GreaterThanTest::testFailure
Failed asserting that 1 is greater than 2.

/home/sb/GreaterThanTest.php:6

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


assertGreaterThanOrEqual()

assertGreaterThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actual não é maior ou igual ao valor de $expected.

assertAttributeGreaterThanOrEqual() é um invólucro conveniente que usa um atributo public, protected, ou private de uma classe ou objeto como o valor atual.

Exemplo A.27: Utilização de assertGreaterThanOrEqual()

<?php
use PHPUnit\Framework\TestCase;

class GreatThanOrEqualTest extends TestCase
{
    public function testFailure()
    {
        $this->assertGreaterThanOrEqual(2, 1);
    }
}
?>
phpunit GreaterThanOrEqualTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) GreatThanOrEqualTest::testFailure
Failed asserting that 1 is equal to 2 or is greater than 2.

/home/sb/GreaterThanOrEqualTest.php:6

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


assertInfinite()

assertInfinite(mixed $variable[, string $message = ''])

Reporta um erro identificado pela $message se $variable não é INF.

assertFinite() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.28: Utilização de assertInfinite()

<?php
use PHPUnit\Framework\TestCase;

class InfiniteTest extends TestCase
{
    public function testFailure()
    {
        $this->assertInfinite(1);
    }
}
?>
phpunit InfiniteTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) InfiniteTest::testFailure
Failed asserting that 1 is infinite.

/home/sb/InfiniteTest.php:6

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


assertInstanceOf()

assertInstanceOf($expected, $actual[, $message = ''])

Reporta um erro identificado pela $message se $actual não é uma instância de $expected.

assertNotInstanceOf() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeInstanceOf() e assertAttributeNotInstanceOf() são invólucros convenientes que podem ser aplicados a um atributo public, protected, ou private de uma classe ou objeto.

Exemplo A.29: Utilização de assertInstanceOf()

<?php
use PHPUnit\Framework\TestCase;

class InstanceOfTest extends TestCase
{
    public function testFailure()
    {
        $this->assertInstanceOf(RuntimeException::class, new Exception);
    }
}
?>
phpunit InstanceOfTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) InstanceOfTest::testFailure
Failed asserting that Exception Object (...) is an instance of class "RuntimeException".

/home/sb/InstanceOfTest.php:6

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


assertInternalType()

assertInternalType($expected, $actual[, $message = ''])

Reporta um erro identificado pela $message se $actual não é do tipo $expected.

assertNotInternalType() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeInternalType() e assertAttributeNotInternalType() são invólucros convenientes que podem aplicados a um atributo public, protected, ou private de uma classe ou objeto.

Exemplo A.30: Utilização de assertInternalType()

<?php
use PHPUnit\Framework\TestCase;

class InternalTypeTest extends TestCase
{
    public function testFailure()
    {
        $this->assertInternalType('string', 42);
    }
}
?>
phpunit InternalTypeTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) InternalTypeTest::testFailure
Failed asserting that 42 is of type "string".

/home/sb/InternalTypeTest.php:6

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


assertIsReadable()

assertIsReadable(string $filename[, string $message = ''])

Reporta um erro identificado pela $message se o arquivo ou diretório especificado por $filename não é legível.

assertNotIsReadable() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.31: Utilização de assertIsReadable()

<?php
use PHPUnit\Framework\TestCase;

class IsReadableTest extends TestCase
{
    public function testFailure()
    {
        $this->assertIsReadable('/path/to/unreadable');
    }
}
?>
phpunit IsReadableTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) IsReadableTest::testFailure
Failed asserting that "/path/to/unreadable" is readable.

/home/sb/IsReadableTest.php:6

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


assertIsWritable()

assertIsWritable(string $filename[, string $message = ''])

Reporta um erro especificado pela $message se o arquivo ou diretório especificado por $filename não é gravável.

assertNotIsWritable() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.32: Utilização de assertIsWritable()

<?php
use PHPUnit\Framework\TestCase;

class IsWritableTest extends TestCase
{
    public function testFailure()
    {
        $this->assertIsWritable('/path/to/unwritable');
    }
}
?>
phpunit IsWritableTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) IsWritableTest::testFailure
Failed asserting that "/path/to/unwritable" is writable.

/home/sb/IsWritableTest.php:6

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


assertJsonFileEqualsJsonFile()

assertJsonFileEqualsJsonFile(mixed $expectedFile, mixed $actualFile[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actualFile não combina com o valor de $expectedFile.

Exemplo A.33: Utilização de assertJsonFileEqualsJsonFile()

<?php
use PHPUnit\Framework\TestCase;

class JsonFileEqualsJsonFileTest extends TestCase
{
    public function testFailure()
    {
        $this->assertJsonFileEqualsJsonFile(
          'path/to/fixture/file', 'path/to/actual/file');
    }
}
?>
phpunit JsonFileEqualsJsonFileTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) JsonFileEqualsJsonFile::testFailure
Failed asserting that '{"Mascot":"Tux"}' matches JSON string "["Mascott", "Tux", "OS", "Linux"]".

/home/sb/JsonFileEqualsJsonFileTest.php:5

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.


assertJsonStringEqualsJsonFile()

assertJsonStringEqualsJsonFile(mixed $expectedFile, mixed $actualJson[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actualJson não combina com o valor de $expectedFile.

Exemplo A.34: Utilização de assertJsonStringEqualsJsonFile()

<?php
use PHPUnit\Framework\TestCase;

class JsonStringEqualsJsonFileTest extends TestCase
{
    public function testFailure()
    {
        $this->assertJsonStringEqualsJsonFile(
            'path/to/fixture/file', json_encode(['Mascot' => 'ux'])
        );
    }
}
?>
phpunit JsonStringEqualsJsonFileTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) JsonStringEqualsJsonFile::testFailure
Failed asserting that '{"Mascot":"ux"}' matches JSON string "{"Mascott":"Tux"}".

/home/sb/JsonStringEqualsJsonFileTest.php:5

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.


assertJsonStringEqualsJsonString()

assertJsonStringEqualsJsonString(mixed $expectedJson, mixed $actualJson[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actualJson não combina com o valor de $expectedJson.

Exemplo A.35: Utilização de assertJsonStringEqualsJsonString()

<?php
use PHPUnit\Framework\TestCase;

class JsonStringEqualsJsonStringTest extends TestCase
{
    public function testFailure()
    {
        $this->assertJsonStringEqualsJsonString(
            json_encode(['Mascot' => 'Tux']),
            json_encode(['Mascot' => 'ux'])
        );
    }
}
?>
phpunit JsonStringEqualsJsonStringTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) JsonStringEqualsJsonStringTest::testFailure
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
 stdClass Object (
 -    'Mascot' => 'Tux'
 +    'Mascot' => 'ux'
)

/home/sb/JsonStringEqualsJsonStringTest.php:5

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.


assertLessThan()

assertLessThan(mixed $expected, mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actual não é menor que o valor de $expected.

assertAttributeLessThan() é um invólucro conveniente que usa um atributo public, protected, ou private de uma classe ou objeto como o valor atual.

Exemplo A.36: Utilização de assertLessThan()

<?php
use PHPUnit\Framework\TestCase;

class LessThanTest extends TestCase
{
    public function testFailure()
    {
        $this->assertLessThan(1, 2);
    }
}
?>
phpunit LessThanTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) LessThanTest::testFailure
Failed asserting that 2 is less than 1.

/home/sb/LessThanTest.php:6

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


assertLessThanOrEqual()

assertLessThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se o valor de $actual não é menor ou igual ao valor de $expected.

assertAttributeLessThanOrEqual() é um invólucro conveniente que usa um atributo public, protected, ou private de uma classe ou objeto como o valor atual.

Exemplo A.37: Utilização de assertLessThanOrEqual()

<?php
use PHPUnit\Framework\TestCase;

class LessThanOrEqualTest extends TestCase
{
    public function testFailure()
    {
        $this->assertLessThanOrEqual(1, 2);
    }
}
?>
phpunit LessThanOrEqualTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) LessThanOrEqualTest::testFailure
Failed asserting that 2 is equal to 1 or is less than 1.

/home/sb/LessThanOrEqualTest.php:6

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


assertNan()

assertNan(mixed $variable[, string $message = ''])

Reporta um erro identificado pela $message se $variable não é NAN.

Exemplo A.38: Usage of assertNan()

<?php
use PHPUnit\Framework\TestCase;

class NanTest extends TestCase
{
    public function testFailure()
    {
        $this->assertNan(1);
    }
}
?>
phpunit NanTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) NanTest::testFailure
Failed asserting that 1 is nan.

/home/sb/NanTest.php:6

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


assertNull()

assertNull(mixed $variable[, string $message = ''])

Reporta um erro identificado pela $message se o $variable não é null.

assertNotNull() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.39: Utilização de assertNull()

<?php
use PHPUnit\Framework\TestCase;

class NullTest extends TestCase
{
    public function testFailure()
    {
        $this->assertNull('foo');
    }
}
?>
phpunit NotNullTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) NullTest::testFailure
Failed asserting that 'foo' is null.

/home/sb/NotNullTest.php:6

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


assertObjectHasAttribute()

assertObjectHasAttribute(string $attributeName, object $object[, string $message = ''])

Reporta um erro identificado pela $message se $object->attributeName não existir.

assertObjectNotHasAttribute() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.40: Utilização de assertObjectHasAttribute()

<?php
use PHPUnit\Framework\TestCase;

class ObjectHasAttributeTest extends TestCase
{
    public function testFailure()
    {
        $this->assertObjectHasAttribute('foo', new stdClass);
    }
}
?>
phpunit ObjectHasAttributeTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) ObjectHasAttributeTest::testFailure
Failed asserting that object of class "stdClass" has attribute "foo".

/home/sb/ObjectHasAttributeTest.php:6

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


assertRegExp()

assertRegExp(string $pattern, string $string[, string $message = ''])

Reporta um erro identificado pela $message se $string não combina com a expressão regular $pattern.

assertNotRegExp() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.41: Utilização de assertRegExp()

<?php
use PHPUnit\Framework\TestCase;

class RegExpTest extends TestCase
{
    public function testFailure()
    {
        $this->assertRegExp('/foo/', 'bar');
    }
}
?>
phpunit RegExpTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) RegExpTest::testFailure
Failed asserting that 'bar' matches PCRE pattern "/foo/".

/home/sb/RegExpTest.php:6

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


assertStringMatchesFormat()

assertStringMatchesFormat(string $format, string $string[, string $message = ''])

Reporta um erro identificado pela $message se a $string não combina com a string $format.

assertStringNotMatchesFormat() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.42: Utilização de assertStringMatchesFormat()

<?php
use PHPUnit\Framework\TestCase;

class StringMatchesFormatTest extends TestCase
{
    public function testFailure()
    {
        $this->assertStringMatchesFormat('%i', 'foo');
    }
}
?>
phpunit StringMatchesFormatTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) StringMatchesFormatTest::testFailure
Failed asserting that 'foo' matches PCRE pattern "/^[+-]?\d+$/s".

/home/sb/StringMatchesFormatTest.php:6

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


A string de formato pode conter os seguintes substitutos (placeholders):

  • %e: Representa um separador de diretório, por exemplo / no Linux.

  • %s: Um ou mais de qualquer coisa (caractere ou espaço em branco) exceto o caractere de fim de linha.

  • %S: Zero ou mais de qualquer coisa (caractere ou espaço em branco) exceto o caractere de fim de linha.

  • %a: Um ou mais de qualquer coisa (caractere ou espaço em branco) incluindo o caractere de fim de linha.

  • %A: Zero ou mais de qualquer coisa (caractere ou espaço em branco) incluindo o caractere de fim de linha.

  • %w: Zero ou mais caracteres de espaços em branco.

  • %i: Um valor inteiro assinado, por exemplo +3142, -3142.

  • %d: Um valor inteiro não-assinado, por exemplo 123456.

  • %x: Um ou mais caracteres hexadecimais. Isto é, caracteres na classe 0-9, a-f, A-F.

  • %f: Um número de ponto flutuante, por exemplo: 3.142, -3.142, 3.142E-10, 3.142e+10.

  • %c: Um único caractere de qualquer ordem.

assertStringMatchesFormatFile()

assertStringMatchesFormatFile(string $formatFile, string $string[, string $message = ''])

Reporta um erro identificado pela $message se a $string não combina com o conteúdo do $formatFile.

assertStringNotMatchesFormatFile() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.43: Utilização de assertStringMatchesFormatFile()

<?php
use PHPUnit\Framework\TestCase;

class StringMatchesFormatFileTest extends TestCase
{
    public function testFailure()
    {
        $this->assertStringMatchesFormatFile('/path/to/expected.txt', 'foo');
    }
}
?>
phpunit StringMatchesFormatFileTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) StringMatchesFormatFileTest::testFailure
Failed asserting that 'foo' matches PCRE pattern "/^[+-]?\d+
$/s".

/home/sb/StringMatchesFormatFileTest.php:6

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


assertSame()

assertSame(mixed $expected, mixed $actual[, string $message = ''])

Reporta um erro identificado pela $message se as variáveis $expected e $actual não tem o mesmo tipo e valor.

assertNotSame() é o inverso desta asserção e recebe os mesmos argumentos.

assertAttributeSame() e assertAttributeNotSame() são invólucros convenientes que usam um atributo public, protected, ou private de uma classe ou objeto como o valor atual.

Exemplo A.44: Utilização de assertSame()

<?php
use PHPUnit\Framework\TestCase;

class SameTest extends TestCase
{
    public function testFailure()
    {
        $this->assertSame('2204', 2204);
    }
}
?>
phpunit SameTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) SameTest::testFailure
Failed asserting that 2204 is identical to '2204'.

/home/sb/SameTest.php:6

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


assertSame(object $expected, object $actual[, string $message = ''])

Reporta um erro identificado pela $message se as variáveis $expected e $actual não referenciam o mesmo objeto.

Exemplo A.45: Utilização de assertSame() com objetos

<?php
use PHPUnit\Framework\TestCase;

class SameTest extends TestCase
{
    public function testFailure()
    {
        $this->assertSame(new stdClass, new stdClass);
    }
}
?>
phpunit SameTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 4.75Mb

There was 1 failure:

1) SameTest::testFailure
Failed asserting that two variables reference the same object.

/home/sb/SameTest.php:6

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


assertStringEndsWith()

assertStringEndsWith(string $suffix, string $string[, string $message = ''])

Reporta um erro identificado pela $message se a $string não termina com $suffix.

assertStringEndsNotWith() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.46: Utilização de assertStringEndsWith()

<?php
use PHPUnit\Framework\TestCase;

class StringEndsWithTest extends TestCase
{
    public function testFailure()
    {
        $this->assertStringEndsWith('suffix', 'foo');
    }
}
?>
phpunit StringEndsWithTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 1 second, Memory: 5.00Mb

There was 1 failure:

1) StringEndsWithTest::testFailure
Failed asserting that 'foo' ends with "suffix".

/home/sb/StringEndsWithTest.php:6

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


assertStringEqualsFile()

assertStringEqualsFile(string $expectedFile, string $actualString[, string $message = ''])

Reporta um erro identificado pela $message se o arquivo especificado por $expectedFile não tem $actualString como seu conteúdo.

assertStringNotEqualsFile() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.47: Utilização de assertStringEqualsFile()

<?php
use PHPUnit\Framework\TestCase;

class StringEqualsFileTest extends TestCase
{
    public function testFailure()
    {
        $this->assertStringEqualsFile('/home/sb/expected', 'actual');
    }
}
?>
phpunit StringEqualsFileTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) StringEqualsFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'expected
-'
+'actual'

/home/sb/StringEqualsFileTest.php:6

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


assertStringStartsWith()

assertStringStartsWith(string $prefix, string $string[, string $message = ''])

Reporta um erro identificado pela $message se a $string não inicia com $prefix.

assertStringStartsNotWith() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.48: Utilização de assertStringStartsWith()

<?php
use PHPUnit\Framework\TestCase;

class StringStartsWithTest extends TestCase
{
    public function testFailure()
    {
        $this->assertStringStartsWith('prefix', 'foo');
    }
}
?>
phpunit StringStartsWithTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) StringStartsWithTest::testFailure
Failed asserting that 'foo' starts with "prefix".

/home/sb/StringStartsWithTest.php:6

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


assertThat()

Asserções mais complexas podem ser formuladas usando as classes PHPUnit_Framework_Constraint. Elas podem ser avaliadas usando o método assertThat(). Exemplo A.49 mostra como as restrições logicalNot() e equalTo() podem ser usadas para expressar a mesma asserção como assertNotEquals().

assertThat(mixed $value, PHPUnit_Framework_Constraint $constraint[, $message = ''])

Reporta um erro identificado pela $message se o$value não combina com a $constraint.

Exemplo A.49: Utilização de assertThat()

<?php
use PHPUnit\Framework\TestCase;

class BiscuitTest extends TestCase
{
    public function testEquals()
    {
        $theBiscuit = new Biscuit('Ginger');
        $myBiscuit  = new Biscuit('Ginger');

        $this->assertThat(
          $theBiscuit,
          $this->logicalNot(
            $this->equalTo($myBiscuit)
          )
        );
    }
}
?>


Tabela A.1 mostra as classes PHPUnit_Framework_Constraint disponíveis.

Tabela A.1. Restrições

RestriçãoSignificado
PHPUnit_Framework_Constraint_Attribute attribute(PHPUnit_Framework_Constraint $constraint, $attributeName)Restrição que aplica outra restrição a um atributo de uma classe ou objeto.
PHPUnit_Framework_Constraint_IsAnything anything()Restrição que aceita qualquer valor de entrada.
PHPUnit_Framework_Constraint_ArrayHasKey arrayHasKey(mixed $key)Restrição que assevera que o array foi avaliado a ter uma dada chave.
PHPUnit_Framework_Constraint_TraversableContains contains(mixed $value)Restrição que assevera que o array ou objeto que implementa a interface Iterator foi avaliado para conter um dado valor.
PHPUnit_Framework_Constraint_TraversableContainsOnly containsOnly(string $type)Restrição que assevera que o array ou objeto que implementa a interface Iterator foi avaliado para conter somente valores de um dado tipo.
PHPUnit_Framework_Constraint_TraversableContainsOnly containsOnlyInstancesOf(string $classname)Restrição que assevera que o array ou objeto que implementa a interface Iterator foi avaliado para conter somente instâncias de um dado nome de classe.
PHPUnit_Framework_Constraint_IsEqual equalTo($value, $delta = 0, $maxDepth = 10)Restrição que verifica se um valor é igual a outro.
PHPUnit_Framework_Constraint_Attribute attributeEqualTo($attributeName, $value, $delta = 0, $maxDepth = 10)Restrição que verifica se um valor é igual a um atributo de uma classe ou objeto.
PHPUnit_Framework_Constraint_DirectoryExists directoryExists()Restrição que verifica se o diretório que foi avaliado existe.
PHPUnit_Framework_Constraint_FileExists fileExists()Restrição que verifica se o arquivo(nome) que foi avaliado existe.
PHPUnit_Framework_Constraint_IsReadable isReadable()Restrição que verifica se o arquivo(nome) que foi avaliado é legível.
PHPUnit_Framework_Constraint_IsWritable isWritable()Restrição que verifica se o arquivo(nome) que foi avaliado é gravável.
PHPUnit_Framework_Constraint_GreaterThan greaterThan(mixed $value)Restrição que assevera que o valor que foi avaliado é maior que um dado valor.
PHPUnit_Framework_Constraint_Or greaterThanOrEqual(mixed $value)Restrição que assevera que o valor que foi avaliado é maior ou igual a um dado valor.
PHPUnit_Framework_Constraint_ClassHasAttribute classHasAttribute(string $attributeName)Restrição que assevera que a classe que foi avaliada tem um dado atributo.
PHPUnit_Framework_Constraint_ClassHasStaticAttribute classHasStaticAttribute(string $attributeName)Restrição que assevera que a classe que foi avaliada tem um dado atributo estático.
PHPUnit_Framework_Constraint_ObjectHasAttribute hasAttribute(string $attributeName)Restrição que assevera que o objeto que foi avaliado tem um dado atributo.
PHPUnit_Framework_Constraint_IsIdentical identicalTo(mixed $value)Restrição que assevera que um valor é idêntico a outro.
PHPUnit_Framework_Constraint_IsFalse isFalse()Restrição que assevera que o valor que foi avaliado é false.
PHPUnit_Framework_Constraint_IsInstanceOf isInstanceOf(string $className)Restrição que assevera que o objeto que foi avaliado é uma instância de uma dada classe.
PHPUnit_Framework_Constraint_IsNull isNull()Restrição que assevera que o valor que foi avaliado é null.
PHPUnit_Framework_Constraint_IsTrue isTrue()Restrição que assevera que o valor que foi avaliado é true.
PHPUnit_Framework_Constraint_IsType isType(string $type)Restrição que assevera que o valor que foi avaliado é de um tipo especificado.
PHPUnit_Framework_Constraint_LessThan lessThan(mixed $value)Restrição que assevera que o valor que foi avaliado é menor que um dado valor.
PHPUnit_Framework_Constraint_Or lessThanOrEqual(mixed $value)Restrição que assevera que o valor que foi avaliado é menor ou igual a um dado valor.
logicalAnd()Lógico AND.
logicalNot(PHPUnit_Framework_Constraint $constraint)Lógico NOT.
logicalOr()Lógico OR.
logicalXor()Lógico XOR.
PHPUnit_Framework_Constraint_PCREMatch matchesRegularExpression(string $pattern)Restrição que assevera que a string que foi avaliada combina com uma expressão regular.
PHPUnit_Framework_Constraint_StringContains stringContains(string $string, bool $case)Restrição que assevera que a string que foi avaliada contém uma dada string.
PHPUnit_Framework_Constraint_StringEndsWith stringEndsWith(string $suffix)Restrição que assevera que a string que foi avaliada termina com um dado sufixo.
PHPUnit_Framework_Constraint_StringStartsWith stringStartsWith(string $prefix)Restrição que assevera que a string que foi avaliada começa com um dado prefixo.


assertTrue()

assertTrue(bool $condition[, string $message = ''])

Reporta um erro identificado pela $message se a $condition é false.

assertNotTrue() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.50: Utilização de assertTrue()

<?php
use PHPUnit\Framework\TestCase;

class TrueTest extends TestCase
{
    public function testFailure()
    {
        $this->assertTrue(false);
    }
}
?>
phpunit TrueTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) TrueTest::testFailure
Failed asserting that false is true.

/home/sb/TrueTest.php:6

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


assertXmlFileEqualsXmlFile()

assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile[, string $message = ''])

Reporta um erro identificado pela $message se o documento XML em $actualFile não é igual ao documento XML em $expectedFile.

assertXmlFileNotEqualsXmlFile() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.51: Utilização de assertXmlFileEqualsXmlFile()

<?php
use PHPUnit\Framework\TestCase;

class XmlFileEqualsXmlFileTest extends TestCase
{
    public function testFailure()
    {
        $this->assertXmlFileEqualsXmlFile(
          '/home/sb/expected.xml', '/home/sb/actual.xml');
    }
}
?>
phpunit XmlFileEqualsXmlFileTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) XmlFileEqualsXmlFileTest::testFailure
Failed asserting that two DOM documents are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
 <foo>
-  <bar/>
+  <baz/>
 </foo>

/home/sb/XmlFileEqualsXmlFileTest.php:7

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.


assertXmlStringEqualsXmlFile()

assertXmlStringEqualsXmlFile(string $expectedFile, string $actualXml[, string $message = ''])

Reporta um erro identificado pela $message se o documento XML em $actualXml não é igual ao documento XML em $expectedFile.

assertXmlStringNotEqualsXmlFile() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.52: Utilização de assertXmlStringEqualsXmlFile()

<?php
use PHPUnit\Framework\TestCase;

class XmlStringEqualsXmlFileTest extends TestCase
{
    public function testFailure()
    {
        $this->assertXmlStringEqualsXmlFile(
          '/home/sb/expected.xml', '<foo><baz/></foo>');
    }
}
?>
phpunit XmlStringEqualsXmlFileTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) XmlStringEqualsXmlFileTest::testFailure
Failed asserting that two DOM documents are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
 <foo>
-  <bar/>
+  <baz/>
 </foo>

/home/sb/XmlStringEqualsXmlFileTest.php:7

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


assertXmlStringEqualsXmlString()

assertXmlStringEqualsXmlString(string $expectedXml, string $actualXml[, string $message = ''])

Reporta um erro identificado pela $message se o documento XML em $actualXml não é igual ao documento XML em $expectedXml.

assertXmlStringNotEqualsXmlString() é o inverso desta asserção e recebe os mesmos argumentos.

Exemplo A.53: Utilização de assertXmlStringEqualsXmlString()

<?php
use PHPUnit\Framework\TestCase;

class XmlStringEqualsXmlStringTest extends TestCase
{
    public function testFailure()
    {
        $this->assertXmlStringEqualsXmlString(
          '<foo><bar/></foo>', '<foo><baz/></foo>');
    }
}
?>
phpunit XmlStringEqualsXmlStringTest
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) XmlStringEqualsXmlStringTest::testFailure
Failed asserting that two DOM documents are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
 <foo>
-  <bar/>
+  <baz/>
 </foo>

/home/sb/XmlStringEqualsXmlStringTest.php:7

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


Por favor, abra um chamado no GitHub para sugerir melhorias para esta página. Obrigado!

粤公网安备 44190002002837号