W3cubDocs

/CakePHP 4.1

Trait IntegrationTestTrait

A trait intended to make integration tests of your controllers easier.

This test class provides a number of helper methods and features that make dispatching requests and checking their responses simpler. It favours full integration tests over mock objects as you can test more of your code easily and avoid some of the maintenance pitfalls that mock objects create.

Namespace: Cake\TestSuite

Properties summary

  • $_appArgs protected
    array|null

    The customized application constructor arguments.

  • $_appClass protected
    string|null

    The customized application class name.

  • $_controller protected
    \Cake\Controller\Controller

    The controller used in the last request.

  • $_cookie protected
    array

    Cookie data to use in the next request.

  • string|null
  • $_csrfToken protected
    bool

    Boolean flag for whether or not the request should have a CSRF token added.

  • $_exception protected
    \Throwable|null

    The exception being thrown if the case.

  • $_flashMessages protected
    array|null

    Stored flash messages before render

  • $_layoutName protected
    string

    The last rendered layout

  • $_request protected
    array

    The data used to build the next request.

  • $_requestSession protected
    \Cake\Http\Session

    The session instance from the last request

  • $_response protected
    \Psr\Http\Message\ResponseInterface

    The response for the most recent request.

  • bool

    Boolean flag for whether or not the request should re-store flash messages

  • $_securityToken protected
    bool

    Boolean flag for whether or not the request should have a SecurityComponent token added.

  • $_session protected
    array

    Session data to use in the next request.

  • $_unlockedFields protected
    string[]

    List of fields that are excluded from field validation.

  • $_validCiphers protected
    string[]

    Valid cipher names for encrypted cookies.

  • $_viewName protected
    string

    The last rendered view

Method Summary

Method Detail

_addTokens() protected

_addTokens(string $url, array $data)

Add the CSRF and Security Component tokens if necessary.

Parameters

string $url

The URL the form is being submitted on.

array $data

The request body data.

Returns

array

The request body with tokens added.

_buildRequest() protected

_buildRequest(string $url, mixed $method, mixed $data)

Creates a request object with the configured options and parameters.

Parameters

string $url

The URL

string $method

The HTTP method

string|array $data optional

The request data.

Returns

array

The request context

_castToString() protected

_castToString(array $data)

Recursively casts all data to string as that is how data would be POSTed in the real world

Parameters

array $data

POST data

Returns

array

_checkCipher() protected

_checkCipher(string $encrypt)

Helper method for validating encryption cipher names.

Parameters

string $encrypt

The cipher name.

Throws

RuntimeException
When an invalid cipher is provided.

_decode() protected

_decode(string $value, mixed $encrypt, ?string $key)

Decodes and decrypts a single value.

Parameters

string $value

The value to decode & decrypt.

string|false $encrypt

The encryption cipher to use.

string|null $key

Used as the security salt if specified.

Returns

string|array

Decoded values.

_decrypt() protected

_decrypt(mixed $values, mixed $mode, ?string $key)

Decrypts $value using public $type method in Security class

Parameters

string[]|string $values

Values to decrypt

string|false $mode

Encryption mode

string|null $key optional

Used as the security salt if specified.

Returns

string|array

Decrypted values

_encrypt() protected

_encrypt(mixed $value, mixed $encrypt, ?string $key)

Encrypts $value using public $type method in Security class

Parameters

string|array $value

Value to encrypt

string|false $encrypt

Encryption mode to use. False disabled encryption.

string|null $key optional

Used as the security salt if specified.

Returns

string

Encoded values

_explode() protected

_explode(string $string)

Explode method to return array from string set in CookieComponent::_implode() Maintains reading backwards compatibility with 1.x CookieComponent::_implode().

Parameters

string $string

A string containing JSON encoded data, or a bare string.

Returns

string|array

Map of key and values

_getBodyAsString() protected

_getBodyAsString()

Get the response body as string

Returns

string

The response body.

_getCookieEncryptionKey() protected

_getCookieEncryptionKey()

Returns the encryption key to be used.

Returns

string

_handleError() protected

_handleError(\Throwable $exception)

Attempts to render an error response for a given exception.

This method will attempt to use the configured exception renderer. If that class does not exist, the built-in renderer will be used.

Parameters

\Throwable $exception

Exception to handle.

_implode() protected

_implode(array $array)

Implode method to keep keys are multidimensional arrays

Parameters

array $array

Map of key and values

Returns

string

A JSON encoded string.

_makeDispatcher() protected

_makeDispatcher()

Get the correct dispatcher instance.

Returns

\Cake\TestSuite\MiddlewareDispatcher

A dispatcher instance

_sendRequest() protected

_sendRequest(mixed $url, mixed $method, mixed $data)

Creates and send the request into a Dispatcher instance.

Receives and stores the response for future inspection.

Parameters

string|array $url

The URL

string $method

The HTTP method

string|array $data optional

The request data.

Throws

PHPUnit\Exception|\Throwable

_url() protected

_url(string $url)

Creates a valid request url and parameter array more like Request::_url()

Parameters

string $url

The URL

Returns

array

Qualified URL, the query parameters, and host data

assertContentType() public

assertContentType(string $type, string $message)

Asserts content type

Parameters

string $type

The content-type to check for.

string $message optional

The failure message that will be appended to the generated message.

assertCookie() public

assertCookie(mixed $expected, string $name, string $message)

Asserts cookie values

Parameters

mixed $expected

The expected contents.

string $name

The cookie name.

string $message optional

The failure message that will be appended to the generated message.

assertCookieEncrypted() public

assertCookieEncrypted(mixed $expected, string $name, string $encrypt, ?string $key, string $message)

Asserts cookie values which are encrypted by the CookieComponent.

The difference from assertCookie() is this decrypts the cookie value like the CookieComponent for this assertion.

Parameters

mixed $expected

The expected contents.

string $name

The cookie name.

string $encrypt optional

Encryption mode to use.

string|null $key optional

Encryption key used. Defaults to Security.salt.

string $message optional

The failure message that will be appended to the generated message.

See Also

\Cake\Utility\CookieCryptTrait::_encrypt()

assertCookieNotSet() public

assertCookieNotSet(string $cookie, string $message)

Asserts a cookie has not been set in the response

Parameters

string $cookie

The cookie name to check

string $message optional

The failure message that will be appended to the generated message.

assertFileResponse() public

assertFileResponse(string $expected, string $message)

Asserts that a file with the given name was sent in the response

Parameters

string $expected

The absolute file path that should be sent in the response.

string $message optional

The failure message that will be appended to the generated message.

assertFlashElement() public

assertFlashElement(string $expected, string $key, string $message)

Asserts a flash element was set

Parameters

string $expected

Expected element name

string $key optional

Flash key

string $message optional

Assertion failure message

assertFlashElementAt() public

assertFlashElementAt(int $at, string $expected, string $key, string $message)

Asserts a flash element was set at a certain index

Parameters

int $at

Flash index

string $expected

Expected element name

string $key optional

Flash key

string $message optional

Assertion failure message

assertFlashMessage() public

assertFlashMessage(string $expected, string $key, string $message)

Asserts a flash message was set

Parameters

string $expected

Expected message

string $key optional

Flash key

string $message optional

Assertion failure message

assertFlashMessageAt() public

assertFlashMessageAt(int $at, string $expected, string $key, string $message)

Asserts a flash message was set at a certain index

Parameters

int $at

Flash index

string $expected

Expected message

string $key optional

Flash key

string $message optional

Assertion failure message

assertHeader() public

assertHeader(string $header, string $content, string $message)

Asserts response headers

Parameters

string $header

The header to check

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

assertHeaderContains() public

assertHeaderContains(string $header, string $content, string $message)

Asserts response header contains a string

Parameters

string $header

The header to check

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

assertHeaderNotContains() public

assertHeaderNotContains(string $header, string $content, string $message)

Asserts response header does not contain a string

Parameters

string $header

The header to check

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

assertLayout() public

assertLayout(string $content, string $message)

Asserts that the search string was in the layout name.

Parameters

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

assertNoRedirect() public

assertNoRedirect(string $message)

Asserts that the Location header is not set.

Parameters

string $message optional

The failure message that will be appended to the generated message.

assertRedirect() public

assertRedirect(mixed $url, mixed $message)

Asserts that the Location header is correct. Comparison is made against a full URL.

Parameters

string|array|null $url optional

The URL you expected the client to go to. This can either be a string URL or an array compatible with Router::url(). Use null to simply check for the existence of this header.

string $message optional

The failure message that will be appended to the generated message.

assertRedirectContains() public

assertRedirectContains(string $url, string $message)

Asserts that the Location header contains a substring

Parameters

string $url

The URL you expected the client to go to.

string $message optional

The failure message that will be appended to the generated message.

assertRedirectEquals() public

assertRedirectEquals(mixed $url, mixed $message)

Asserts that the Location header is correct. Comparison is made against exactly the URL provided.

Parameters

string|array|null $url optional

The URL you expected the client to go to. This can either be a string URL or an array compatible with Router::url(). Use null to simply check for the existence of this header.

string $message optional

The failure message that will be appended to the generated message.

assertRedirectNotContains() public

assertRedirectNotContains(string $url, string $message)

Asserts that the Location header does not contain a substring

Parameters

string $url

The URL you expected the client to go to.

string $message optional

The failure message that will be appended to the generated message.

assertResponseCode() public

assertResponseCode(int $code, string $message)

Asserts a specific response status code.

Parameters

int $code

Status code to assert.

string $message optional

Custom message for failure.

assertResponseContains() public

assertResponseContains(string $content, string $message, bool $ignoreCase)

Asserts content exists in the response body.

Parameters

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

bool $ignoreCase optional

A flag to check whether we should ignore case or not.

assertResponseEmpty() public

assertResponseEmpty(string $message)

Assert response content is empty.

Parameters

string $message optional

The failure message that will be appended to the generated message.

assertResponseEquals() public

assertResponseEquals(mixed $content, mixed $message)

Asserts content in the response body equals.

Parameters

mixed $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

assertResponseError() public

assertResponseError(string $message)

Asserts that the response status code is in the 4xx range.

Parameters

string $message optional

Custom message for failure.

assertResponseFailure() public

assertResponseFailure(string $message)

Asserts that the response status code is in the 5xx range.

Parameters

string $message optional

Custom message for failure.

assertResponseNotContains() public

assertResponseNotContains(string $content, string $message, bool $ignoreCase)

Asserts content does not exist in the response body.

Parameters

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

bool $ignoreCase optional

A flag to check whether we should ignore case or not.

assertResponseNotEmpty() public

assertResponseNotEmpty(string $message)

Assert response content is not empty.

Parameters

string $message optional

The failure message that will be appended to the generated message.

assertResponseNotEquals() public

assertResponseNotEquals(mixed $content, mixed $message)

Asserts content in the response body not equals.

Parameters

mixed $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

assertResponseNotRegExp() public

assertResponseNotRegExp(string $pattern, string $message)

Asserts that the response body does not match a given regular expression.

Parameters

string $pattern

The pattern to compare against.

string $message optional

The failure message that will be appended to the generated message.

assertResponseOk() public

assertResponseOk(string $message)

Asserts that the response status code is in the 2xx range.

Parameters

string $message optional

Custom message for failure.

assertResponseRegExp() public

assertResponseRegExp(string $pattern, string $message)

Asserts that the response body matches a given regular expression.

Parameters

string $pattern

The pattern to compare against.

string $message optional

The failure message that will be appended to the generated message.

assertResponseSuccess() public

assertResponseSuccess(string $message)

Asserts that the response status code is in the 2xx/3xx range.

Parameters

string $message optional

Custom message for failure.

assertSession() public

assertSession(mixed $expected, string $path, string $message)

Asserts session contents

Parameters

mixed $expected

The expected contents.

string $path

The session data path. Uses Hash::get() compatible notation

string $message optional

The failure message that will be appended to the generated message.

assertSessionHasKey() public

assertSessionHasKey(string $path, string $message)

Asserts session key exists.

Parameters

string $path

The session data path. Uses Hash::get() compatible notation.

string $message optional

The failure message that will be appended to the generated message.

assertSessionNotHasKey() public

assertSessionNotHasKey(string $path, string $message)

Asserts a session key does not exist.

Parameters

string $path

The session data path. Uses Hash::get() compatible notation.

string $message optional

The failure message that will be appended to the generated message.

assertTemplate() public

assertTemplate(string $content, string $message)

Asserts that the search string was in the template name.

Parameters

string $content

The content to check for.

string $message optional

The failure message that will be appended to the generated message.

cleanup() public

cleanup()

Clears the state used for requests.

configApplication() public

configApplication(string $class, ?array $constructorArgs)

Configure the application class to use in integration tests.

Parameters

string $class

The application class name.

array|null $constructorArgs

The constructor arguments for your application class.

configRequest() public

configRequest(array $data)

Configures the data for the next request.

This data is cleared in the tearDown() method.

You can call this method multiple times to append into the current state.

Parameters

array $data

The request data to use.

controllerSpy() public

controllerSpy(\Cake\Event\EventInterface $event, ?\Cake\Controller\Controller $controller)

Adds additional event spies to the controller/view event manager.

Parameters

\Cake\Event\EventInterface $event

A dispatcher event.

\Cake\Controller\Controller|null $controller optional

Controller instance.

cookie(string $name, mixed $value)

Sets a request cookie for future requests.

This method lets you configure the session data you want to be used for requests that follow. The session state is reset in each tearDown().

You can call this method multiple times to append into the current state.

Parameters

string $name

The cookie name to use.

mixed $value

The value of the cookie.

cookieEncrypted() public

cookieEncrypted(string $name, mixed $value, mixed $encrypt, mixed $key)

Sets a encrypted request cookie for future requests.

The difference from cookie() is this encrypts the cookie value like the CookieComponent.

Parameters

string $name

The cookie name to use.

mixed $value

The value of the cookie.

string|false $encrypt optional

Encryption mode to use.

string|null $key optional

Encryption key used. Defaults to Security.salt.

See Also

\Cake\Utility\CookieCryptTrait::_encrypt()

delete() public

delete(mixed $url)

Performs a DELETE request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

disableErrorHandlerMiddleware() public

disableErrorHandlerMiddleware()

Disable the error handler middleware.

By using this function, exceptions are no longer caught by the ErrorHandlerMiddleware and are instead re-thrown by the TestExceptionRenderer. This can be helpful when trying to diagnose/debug unexpected failures in test cases.

enableCsrfToken() public

enableCsrfToken()

Calling this method will add a CSRF token to the request.

Both the POST data and cookie will be populated when this option is enabled. The default parameter names will be used.

enableRetainFlashMessages() public

enableRetainFlashMessages()

Calling this method will re-store flash messages into the test session after being removed by the FlashHelper

enableSecurityToken() public

enableSecurityToken()

Calling this method will enable a SecurityComponent compatible token to be added to request data. This lets you easily test actions protected by SecurityComponent.

extractExceptionMessage() protected

extractExceptionMessage(\Exception $exception)

Extract verbose message for existing exception

Parameters

\Exception $exception

Exception to extract

Returns

string

extractVerboseMessage() protected

extractVerboseMessage(string $message)

Inspect controller to extract possible causes of the failed assertion

Parameters

string $message

Original message to use as a base

Returns

string

get() public

get(mixed $url)

Performs a GET request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

getSession() protected

getSession()

Returns

\Cake\TestSuite\TestSession
head(mixed $url)

Performs a HEAD request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

options() public

options(mixed $url)

Performs an OPTIONS request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

patch() public

patch(mixed $url, mixed $data)

Performs a PATCH request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

string|array $data optional

The data for the request.

post() public

post(mixed $url, mixed $data)

Performs a POST request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

string|array $data optional

The data for the request.

put() public

put(mixed $url, mixed $data)

Performs a PUT request using the current request data.

The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.

Parameters

string|array $url

The URL to request.

string|array $data optional

The data for the request.

session() public

session(array $data)

Sets session data.

This method lets you configure the session data you want to be used for requests that follow. The session state is reset in each tearDown().

You can call this method multiple times to append into the current state.

Parameters

array $data

The session data to use.

setUnlockedFields() public

setUnlockedFields(array $unlockedFields)

Set list of fields that are excluded from field validation.

Parameters

string[] $unlockedFields optional

List of fields that are excluded from field validation.

viewVariable() public

viewVariable(string $name)

Fetches a view variable by name.

If the view variable does not exist, null will be returned.

Parameters

string $name

The view variable to get.

Returns

mixed

The view variable if set.

Property Detail

$_appArgs protected

The customized application constructor arguments.

Type

array|null

$_appClass protected

The customized application class name.

Type

string|null

$_controller protected

The controller used in the last request.

Type

\Cake\Controller\Controller

Cookie data to use in the next request.

Type

array

$_cookieEncryptionKey protected

Type

string|null

$_csrfToken protected

Boolean flag for whether or not the request should have a CSRF token added.

Type

bool

$_exception protected

The exception being thrown if the case.

Type

\Throwable|null

$_flashMessages protected

Stored flash messages before render

Type

array|null

$_layoutName protected

The last rendered layout

Type

string

$_request protected

The data used to build the next request.

Type

array

$_requestSession protected

The session instance from the last request

Type

\Cake\Http\Session

$_response protected

The response for the most recent request.

Type

\Psr\Http\Message\ResponseInterface

$_retainFlashMessages protected

Boolean flag for whether or not the request should re-store flash messages

Type

bool

$_securityToken protected

Boolean flag for whether or not the request should have a SecurityComponent token added.

Type

bool

$_session protected

Session data to use in the next request.

Type

array

$_unlockedFields protected

List of fields that are excluded from field validation.

Type

string[]

$_validCiphers protected

Valid cipher names for encrypted cookies.

Type

string[]

$_viewName protected

The last rendered view

Type

string

© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.1/trait-Cake.TestSuite.IntegrationTestTrait.html