Fr3nch13/CakePHP Utilities

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.

Table of Contents

Properties

$_controller  : Controller|null
The controller used in the last request.
$_cookie  : array<string|int, mixed>
Cookie data to use in the next request.
$_cookieEncryptionKey  : string|null
$_csrfKeyName  : string
The name that will be used when retrieving the csrf token.
$_csrfToken  : bool
Boolean flag for whether the request should have a CSRF token added.
$_exception  : Throwable|null
The exception being thrown if the case.
$_flashMessages  : array<string|int, mixed>
Stored flash messages before render
$_layoutName  : string
The last rendered layout
$_request  : array<string|int, mixed>
The data used to build the next request.
$_requestSession  : Session
The session instance from the last request
$_response  : ResponseInterface|null
The response for the most recent request.
$_retainFlashMessages  : bool
Boolean flag for whether the request should re-store flash messages
$_securityToken  : bool
Boolean flag for whether the request should have a SecurityComponent token added.
$_session  : array<string|int, mixed>
Session data to use in the next request.
$_unlockedFields  : array<string|int, string>
List of fields that are excluded from field validation.
$_viewName  : string
The last rendered view

Methods

assertContentType()  : void
Asserts content type
assertCookie()  : void
Asserts cookie values
assertCookieEncrypted()  : void
Asserts cookie values which are encrypted by the CookieComponent.
assertCookieNotSet()  : void
Asserts a cookie has not been set in the response
assertFileResponse()  : void
Asserts that a file with the given name was sent in the response
assertFlashElement()  : void
Asserts a flash element was set
assertFlashElementAt()  : void
Asserts a flash element was set at a certain index
assertFlashMessage()  : void
Asserts a flash message was set
assertFlashMessageAt()  : void
Asserts a flash message was set at a certain index
assertHeader()  : void
Asserts response headers
assertHeaderContains()  : void
Asserts response header contains a string
assertHeaderNotContains()  : void
Asserts response header does not contain a string
assertLayout()  : void
Asserts that the search string was in the layout name.
assertNoRedirect()  : void
Asserts that the Location header is not set.
assertRedirect()  : void
Asserts that the Location header is correct. Comparison is made against a full URL.
assertRedirectContains()  : void
Asserts that the Location header contains a substring
assertRedirectEquals()  : void
Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
assertRedirectNotContains()  : void
Asserts that the Location header does not contain a substring
assertResponseCode()  : void
Asserts a specific response status code.
assertResponseContains()  : void
Asserts content exists in the response body.
assertResponseEmpty()  : void
Assert response content is empty.
assertResponseEquals()  : void
Asserts content in the response body equals.
assertResponseError()  : void
Asserts that the response status code is in the 4xx range.
assertResponseFailure()  : void
Asserts that the response status code is in the 5xx range.
assertResponseNotContains()  : void
Asserts content does not exist in the response body.
assertResponseNotEmpty()  : void
Assert response content is not empty.
assertResponseNotEquals()  : void
Asserts content in the response body not equals.
assertResponseNotRegExp()  : void
Asserts that the response body does not match a given regular expression.
assertResponseOk()  : void
Asserts that the response status code is in the 2xx range.
assertResponseRegExp()  : void
Asserts that the response body matches a given regular expression.
assertResponseSuccess()  : void
Asserts that the response status code is in the 2xx/3xx range.
assertSession()  : void
Asserts session contents
assertSessionHasKey()  : void
Asserts session key exists.
assertSessionNotHasKey()  : void
Asserts a session key does not exist.
assertTemplate()  : void
Asserts that the search string was in the template name.
cleanup()  : void
Clears the state used for requests.
configRequest()  : void
Configures the data for the *next* request.
controllerSpy()  : void
Adds additional event spies to the controller/view event manager.
cookie()  : void
Sets a request cookie for future requests.
cookieEncrypted()  : void
Sets a encrypted request cookie for future requests.
delete()  : void
Performs a DELETE request using the current request data.
disableErrorHandlerMiddleware()  : void
Disable the error handler middleware.
enableCsrfToken()  : void
Calling this method will add a CSRF token to the request.
enableRetainFlashMessages()  : void
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
enableSecurityToken()  : void
Calling this method will enable a SecurityComponent compatible token to be added to request data. This lets you easily test actions protected by SecurityComponent.
get()  : void
Performs a GET request using the current request data.
head()  : void
Performs a HEAD request using the current request data.
options()  : void
Performs an OPTIONS request using the current request data.
patch()  : void
Performs a PATCH request using the current request data.
post()  : void
Performs a POST request using the current request data.
put()  : void
Performs a PUT request using the current request data.
session()  : void
Sets session data.
setUnlockedFields()  : void
Set list of fields that are excluded from field validation.
viewVariable()  : mixed
Fetches a view variable by name.
_addTokens()  : array<string|int, mixed>
Add the CSRF and Security Component tokens if necessary.
_buildRequest()  : array<string|int, mixed>
Creates a request object with the configured options and parameters.
_castToString()  : array<string|int, mixed>
Recursively casts all data to string as that is how data would be POSTed in the real world
_getBodyAsString()  : string
Get the response body as string
_getCookieEncryptionKey()  : string
Returns the encryption key to be used.
_handleError()  : void
Attempts to render an error response for a given exception.
_makeDispatcher()  : MiddlewareDispatcher
Get the correct dispatcher instance.
_sendRequest()  : void
Creates and send the request into a Dispatcher instance.
_url()  : array<string|int, mixed>
Creates a valid request url and parameter array more like Request::_url()
extractExceptionMessage()  : string
Extract verbose message for existing exception
extractVerboseMessage()  : string
Inspect controller to extract possible causes of the failed assertion
getSession()  : TestSession

Properties

Cookie data to use in the next request.

protected array<string|int, mixed> $_cookie = []

$_csrfKeyName

The name that will be used when retrieving the csrf token.

protected string $_csrfKeyName = 'csrfToken'

$_csrfToken

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

protected bool $_csrfToken = false

$_exception

The exception being thrown if the case.

protected Throwable|null $_exception

$_flashMessages

Stored flash messages before render

protected array<string|int, mixed> $_flashMessages = []

$_request

The data used to build the next request.

protected array<string|int, mixed> $_request = []

$_retainFlashMessages

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

protected bool $_retainFlashMessages = false

$_securityToken

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

protected bool $_securityToken = false

$_session

Session data to use in the next request.

protected array<string|int, mixed> $_session = []

$_unlockedFields

List of fields that are excluded from field validation.

protected array<string|int, string> $_unlockedFields = []

Methods

assertContentType()

Asserts content type

public assertContentType(string $type[, string $message = '' ]) : void
Parameters
$type : string

The content-type to check for.

$message : string = ''

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

assertCookie()

Asserts cookie values

public assertCookie(mixed $expected, string $name[, string $message = '' ]) : void
Parameters
$expected : mixed

The expected contents.

$name : string

The cookie name.

$message : string = ''

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

assertCookieEncrypted()

Asserts cookie values which are encrypted by the CookieComponent.

public assertCookieEncrypted(mixed $expected, string $name[, string $encrypt = 'aes' ][, string|null $key = null ][, string $message = '' ]) : void

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

Parameters
$expected : mixed

The expected contents.

$name : string

The cookie name.

$encrypt : string = 'aes'

Encryption mode to use.

$key : string|null = null

Encryption key used. Defaults to Security.salt.

$message : string = ''

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

Tags
see
CookieCryptTrait::_encrypt()

assertCookieNotSet()

Asserts a cookie has not been set in the response

public assertCookieNotSet(string $cookie[, string $message = '' ]) : void
Parameters
$cookie : string

The cookie name to check

$message : string = ''

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

assertFileResponse()

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

public assertFileResponse(string $expected[, string $message = '' ]) : void
Parameters
$expected : string

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

$message : string = ''

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

assertFlashElement()

Asserts a flash element was set

public assertFlashElement(string $expected[, string $key = 'flash' ][, string $message = '' ]) : void
Parameters
$expected : string

Expected element name

$key : string = 'flash'

Flash key

$message : string = ''

Assertion failure message

assertFlashElementAt()

Asserts a flash element was set at a certain index

public assertFlashElementAt(int $at, string $expected[, string $key = 'flash' ][, string $message = '' ]) : void
Parameters
$at : int

Flash index

$expected : string

Expected element name

$key : string = 'flash'

Flash key

$message : string = ''

Assertion failure message

assertFlashMessage()

Asserts a flash message was set

public assertFlashMessage(string $expected[, string $key = 'flash' ][, string $message = '' ]) : void
Parameters
$expected : string

Expected message

$key : string = 'flash'

Flash key

$message : string = ''

Assertion failure message

assertFlashMessageAt()

Asserts a flash message was set at a certain index

public assertFlashMessageAt(int $at, string $expected[, string $key = 'flash' ][, string $message = '' ]) : void
Parameters
$at : int

Flash index

$expected : string

Expected message

$key : string = 'flash'

Flash key

$message : string = ''

Assertion failure message

assertHeader()

Asserts response headers

public assertHeader(string $header, string $content[, string $message = '' ]) : void
Parameters
$header : string

The header to check

$content : string

The content to check for.

$message : string = ''

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

assertHeaderContains()

Asserts response header contains a string

public assertHeaderContains(string $header, string $content[, string $message = '' ]) : void
Parameters
$header : string

The header to check

$content : string

The content to check for.

$message : string = ''

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

assertHeaderNotContains()

Asserts response header does not contain a string

public assertHeaderNotContains(string $header, string $content[, string $message = '' ]) : void
Parameters
$header : string

The header to check

$content : string

The content to check for.

$message : string = ''

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

assertLayout()

Asserts that the search string was in the layout name.

public assertLayout(string $content[, string $message = '' ]) : void
Parameters
$content : string

The content to check for.

$message : string = ''

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

assertNoRedirect()

Asserts that the Location header is not set.

public assertNoRedirect([string $message = '' ]) : void
Parameters
$message : string = ''

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

assertRedirect()

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

public assertRedirect([array<string|int, mixed>|string|null $url = null ][, string $message = '' ]) : void
Parameters
$url : array<string|int, mixed>|string|null = null

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.

$message : string = ''

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

assertRedirectContains()

Asserts that the Location header contains a substring

public assertRedirectContains(string $url[, string $message = '' ]) : void
Parameters
$url : string

The URL you expected the client to go to.

$message : string = ''

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

assertRedirectEquals()

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

public assertRedirectEquals([array<string|int, mixed>|string|null $url = null ][, string $message = '' ]) : void
Parameters
$url : array<string|int, mixed>|string|null = null

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.

$message : string = ''

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

assertRedirectNotContains()

Asserts that the Location header does not contain a substring

public assertRedirectNotContains(string $url[, string $message = '' ]) : void
Parameters
$url : string

The URL you expected the client to go to.

$message : string = ''

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

assertResponseCode()

Asserts a specific response status code.

public assertResponseCode(int $code[, string $message = '' ]) : void
Parameters
$code : int

Status code to assert.

$message : string = ''

Custom message for failure.

assertResponseContains()

Asserts content exists in the response body.

public assertResponseContains(string $content[, string $message = '' ][, bool $ignoreCase = false ]) : void
Parameters
$content : string

The content to check for.

$message : string = ''

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

$ignoreCase : bool = false

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

assertResponseEmpty()

Assert response content is empty.

public assertResponseEmpty([string $message = '' ]) : void
Parameters
$message : string = ''

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

assertResponseEquals()

Asserts content in the response body equals.

public assertResponseEquals(mixed $content[, string $message = '' ]) : void
Parameters
$content : mixed

The content to check for.

$message : string = ''

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

assertResponseError()

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

public assertResponseError([string $message = '' ]) : void
Parameters
$message : string = ''

Custom message for failure.

assertResponseFailure()

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

public assertResponseFailure([string $message = '' ]) : void
Parameters
$message : string = ''

Custom message for failure.

assertResponseNotContains()

Asserts content does not exist in the response body.

public assertResponseNotContains(string $content[, string $message = '' ][, bool $ignoreCase = false ]) : void
Parameters
$content : string

The content to check for.

$message : string = ''

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

$ignoreCase : bool = false

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

assertResponseNotEmpty()

Assert response content is not empty.

public assertResponseNotEmpty([string $message = '' ]) : void
Parameters
$message : string = ''

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

assertResponseNotEquals()

Asserts content in the response body not equals.

public assertResponseNotEquals(mixed $content[, string $message = '' ]) : void
Parameters
$content : mixed

The content to check for.

$message : string = ''

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

assertResponseNotRegExp()

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

public assertResponseNotRegExp(string $pattern[, string $message = '' ]) : void
Parameters
$pattern : string

The pattern to compare against.

$message : string = ''

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

assertResponseOk()

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

public assertResponseOk([string $message = '' ]) : void
Parameters
$message : string = ''

Custom message for failure.

assertResponseRegExp()

Asserts that the response body matches a given regular expression.

public assertResponseRegExp(string $pattern[, string $message = '' ]) : void
Parameters
$pattern : string

The pattern to compare against.

$message : string = ''

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

assertResponseSuccess()

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

public assertResponseSuccess([string $message = '' ]) : void
Parameters
$message : string = ''

Custom message for failure.

assertSession()

Asserts session contents

public assertSession(mixed $expected, string $path[, string $message = '' ]) : void
Parameters
$expected : mixed

The expected contents.

$path : string

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

$message : string = ''

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

assertSessionHasKey()

Asserts session key exists.

public assertSessionHasKey(string $path[, string $message = '' ]) : void
Parameters
$path : string

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

$message : string = ''

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

assertSessionNotHasKey()

Asserts a session key does not exist.

public assertSessionNotHasKey(string $path[, string $message = '' ]) : void
Parameters
$path : string

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

$message : string = ''

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

assertTemplate()

Asserts that the search string was in the template name.

public assertTemplate(string $content[, string $message = '' ]) : void
Parameters
$content : string

The content to check for.

$message : string = ''

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

cleanup()

Clears the state used for requests.

public cleanup() : void
Tags
after
psalm-suppress

PossiblyNullPropertyAssignmentValue

configRequest()

Configures the data for the *next* request.

public configRequest(array<string|int, mixed> $data) : void

This data is cleared in the tearDown() method.

You can call this method multiple times to append into the current state. Sub-keys like 'headers' will be reset, though.

Parameters
$data : array<string|int, mixed>

The request data to use.

Sets a request cookie for future requests.

public cookie(string $name, mixed $value) : void

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
$name : string

The cookie name to use.

$value : mixed

The value of the cookie.

cookieEncrypted()

Sets a encrypted request cookie for future requests.

public cookieEncrypted(string $name, mixed $value[, string|false $encrypt = 'aes' ][, string|null $key = null ]) : void

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

Parameters
$name : string

The cookie name to use.

$value : mixed

The value of the cookie.

$encrypt : string|false = 'aes'

Encryption mode to use.

$key : string|null = null

Encryption key used. Defaults to Security.salt.

Tags
see
CookieCryptTrait::_encrypt()

delete()

Performs a DELETE request using the current request data.

public delete(array<string|int, mixed>|string $url) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

disableErrorHandlerMiddleware()

Disable the error handler middleware.

public disableErrorHandlerMiddleware() : void

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()

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

public enableCsrfToken([string $cookieName = 'csrfToken' ]) : void

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

Parameters
$cookieName : string = 'csrfToken'

The name of the csrf token cookie.

enableRetainFlashMessages()

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

public enableRetainFlashMessages() : void

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.

public enableSecurityToken() : void

get()

Performs a GET request using the current request data.

public get(array<string|int, mixed>|string $url) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

head()

Performs a HEAD request using the current request data.

public head(array<string|int, mixed>|string $url) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

options()

Performs an OPTIONS request using the current request data.

public options(array<string|int, mixed>|string $url) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

patch()

Performs a PATCH request using the current request data.

public patch(array<string|int, mixed>|string $url[, array<string|int, mixed>|string $data = [] ]) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

$data : array<string|int, mixed>|string = []

The data for the request.

post()

Performs a POST request using the current request data.

public post(array<string|int, mixed>|string $url[, array<string|int, mixed>|string $data = [] ]) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

$data : array<string|int, mixed>|string = []

The data for the request.

put()

Performs a PUT request using the current request data.

public put(array<string|int, mixed>|string $url[, array<string|int, mixed>|string $data = [] ]) : void

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

Parameters
$url : array<string|int, mixed>|string

The URL to request.

$data : array<string|int, mixed>|string = []

The data for the request.

session()

Sets session data.

public session(array<string|int, mixed> $data) : void

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
$data : array<string|int, mixed>

The session data to use.

setUnlockedFields()

Set list of fields that are excluded from field validation.

public setUnlockedFields([array<string|int, string> $unlockedFields = [] ]) : void
Parameters
$unlockedFields : array<string|int, string> = []

List of fields that are excluded from field validation.

viewVariable()

Fetches a view variable by name.

public viewVariable(string $name) : mixed

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

Parameters
$name : string

The view variable to get.

Return values
mixed

The view variable if set.

_addTokens()

Add the CSRF and Security Component tokens if necessary.

protected _addTokens(string $url, array<string|int, mixed> $data) : array<string|int, mixed>
Parameters
$url : string

The URL the form is being submitted on.

$data : array<string|int, mixed>

The request body data.

Return values
array<string|int, mixed>

The request body with tokens added.

_buildRequest()

Creates a request object with the configured options and parameters.

protected _buildRequest(string $url, string $method[, array<string|int, mixed>|string $data = [] ]) : array<string|int, mixed>
Parameters
$url : string

The URL

$method : string

The HTTP method

$data : array<string|int, mixed>|string = []

The request data.

Return values
array<string|int, mixed>

The request context

_castToString()

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

protected _castToString(array<string|int, mixed> $data) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

POST data

Return values
array<string|int, mixed>

_getBodyAsString()

Get the response body as string

protected _getBodyAsString() : string
Return values
string

The response body.

_getCookieEncryptionKey()

Returns the encryption key to be used.

protected _getCookieEncryptionKey() : string
Return values
string

_handleError()

Attempts to render an error response for a given exception.

protected _handleError(Throwable $exception) : void

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

Parameters
$exception : Throwable

Exception to handle.

_makeDispatcher()

Get the correct dispatcher instance.

protected _makeDispatcher() : MiddlewareDispatcher
Return values
MiddlewareDispatcher

A dispatcher instance

_sendRequest()

Creates and send the request into a Dispatcher instance.

protected _sendRequest(array<string|int, mixed>|string $url, string $method[, array<string|int, mixed>|string $data = [] ]) : void

Receives and stores the response for future inspection.

Parameters
$url : array<string|int, mixed>|string

The URL

$method : string

The HTTP method

$data : array<string|int, mixed>|string = []

The request data.

Tags
throws
Exception|Throwable

_url()

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

protected _url(string $url) : array<string|int, mixed>
Parameters
$url : string

The URL

Return values
array<string|int, mixed>

Qualified URL, the query parameters, and host data

extractExceptionMessage()

Extract verbose message for existing exception

protected extractExceptionMessage(Exception $exception) : string
Parameters
$exception : Exception

Exception to extract

Return values
string

extractVerboseMessage()

Inspect controller to extract possible causes of the failed assertion

protected extractVerboseMessage(string $message) : string
Parameters
$message : string

Original message to use as a base

Return values
string

        
On this page

Search results