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.
Property Summary
-
$_appArgs protected
array|nullThe customized application constructor arguments.
-
$_appClass protected
string|nullThe customized application class name.
-
$_controller protected
Cake\Controller\ControllerThe controller used in the last request.
-
$_cookie protected
arrayCookie data to use in the next request.
-
$_cookieEncryptionKey protected
string|null -
$_csrfToken protected
boolBoolean flag for whether or not the request should have a CSRF token added.
-
$_exception protected
Throwable|nullThe exception being thrown if the case.
-
$_flashMessages protected
array|nullStored flash messages before render
-
$_layoutName protected
stringThe last rendered layout
-
$_request protected
arrayThe data used to build the next request.
-
$_requestSession protected
Cake\Http\SessionThe session instance from the last request
-
$_response protected
Psr\Http\Message\ResponseInterfaceThe response for the most recent request.
-
$_retainFlashMessages protected
boolBoolean flag for whether or not the request should re-store flash messages
-
$_securityToken protected
boolBoolean flag for whether or not the request should have a SecurityComponent token added.
-
$_session protected
arraySession 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
stringThe last rendered view
Method Summary
-
_addTokens() protected
Add the CSRF and Security Component tokens if necessary.
-
_buildRequest() protected
Creates a request object with the configured options and parameters.
-
_castToString() protected
Recursively casts all data to string as that is how data would be POSTed in the real world
-
_checkCipher() protected
Helper method for validating encryption cipher names.
-
_decode() protected
Decodes and decrypts a single value.
-
_decrypt() protected
Decrypts $value using public $type method in Security class
-
_encrypt() protected
Encrypts $value using public $type method in Security class
-
_explode() protected
Explode method to return array from string set in CookieComponent::_implode() Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
-
_getBodyAsString() protected
Get the response body as string
-
_getCookieEncryptionKey() protected
Returns the encryption key to be used.
-
_handleError() protected
Attempts to render an error response for a given exception.
-
_implode() protected
Implode method to keep keys are multidimensional arrays
-
_makeDispatcher() protected
Get the correct dispatcher instance.
-
_sendRequest() protected
Creates and send the request into a Dispatcher instance.
-
_url() protected
Creates a valid request url and parameter array more like Request::_url()
-
assertContentType() public
Asserts content type
-
assertCookie() public
Asserts cookie values
-
assertCookieEncrypted() public
Asserts cookie values which are encrypted by the CookieComponent.
-
assertCookieNotSet() public
Asserts a cookie has not been set in the response
-
assertFileResponse() public
Asserts that a file with the given name was sent in the response
-
assertFlashElement() public
Asserts a flash element was set
-
assertFlashElementAt() public
Asserts a flash element was set at a certain index
-
assertFlashMessage() public
Asserts a flash message was set
-
assertFlashMessageAt() public
Asserts a flash message was set at a certain index
-
assertHeader() public
Asserts response headers
-
assertHeaderContains() public
Asserts response header contains a string
-
assertHeaderNotContains() public
Asserts response header does not contain a string
-
assertLayout() public
Asserts that the search string was in the layout name.
-
assertNoRedirect() public
Asserts that the Location header is not set.
-
assertRedirect() public
Asserts that the Location header is correct. Comparison is made against a full URL.
-
assertRedirectContains() public
Asserts that the Location header contains a substring
-
assertRedirectEquals() public
Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
-
assertRedirectNotContains() public
Asserts that the Location header does not contain a substring
-
assertResponseCode() public
Asserts a specific response status code.
-
assertResponseContains() public
Asserts content exists in the response body.
-
assertResponseEmpty() public
Assert response content is empty.
-
assertResponseEquals() public
Asserts content in the response body equals.
-
assertResponseError() public
Asserts that the response status code is in the 4xx range.
-
assertResponseFailure() public
Asserts that the response status code is in the 5xx range.
-
assertResponseNotContains() public
Asserts content does not exist in the response body.
-
assertResponseNotEmpty() public
Assert response content is not empty.
-
assertResponseNotEquals() public
Asserts content in the response body not equals.
-
assertResponseNotRegExp() public
Asserts that the response body does not match a given regular expression.
-
assertResponseOk() public
Asserts that the response status code is in the 2xx range.
-
assertResponseRegExp() public
Asserts that the response body matches a given regular expression.
-
assertResponseSuccess() public
Asserts that the response status code is in the 2xx/3xx range.
-
assertSession() public
Asserts session contents
-
assertTemplate() public
Asserts that the search string was in the template name.
-
cleanup() public
Clears the state used for requests.
-
configApplication() public
Configure the application class to use in integration tests.
-
configRequest() public
Configures the data for the next request.
-
controllerSpy() public
Adds additional event spies to the controller/view event manager.
-
cookie() public
Sets a request cookie for future requests.
-
cookieEncrypted() public
Sets a encrypted request cookie for future requests.
-
delete() public
Performs a DELETE request using the current request data.
-
disableErrorHandlerMiddleware() public
Disable the error handler middleware.
-
enableCsrfToken() public
Calling this method will add a CSRF token to the request.
-
enableRetainFlashMessages() public
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
-
enableSecurityToken() public
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
Extract verbose message for existing exception
-
extractVerboseMessage() protected
Inspect controller to extract possible causes of the failed assertion
-
get() public
Performs a GET request using the current request data.
-
getSession() protected
-
head() public
Performs a HEAD request using the current request data.
-
options() public
Performs an OPTIONS request using the current request data.
-
patch() public
Performs a PATCH request using the current request data.
-
post() public
Performs a POST request using the current request data.
-
put() public
Performs a PUT request using the current request data.
-
session() public
Sets session data.
-
setUnlockedFields() public
Set list of fields that are excluded from field validation.
-
viewVariable() public
Fetches a view variable by name.
Method Detail
_addTokens() ¶ protected
_addTokens(string $url, array $data): array
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_buildRequest() ¶ protected
_buildRequest(string $url, string $method, string|array $data = []): array
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_castToString() ¶ protected
_castToString(array $data): array
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): void
Helper method for validating encryption cipher names.
Parameters
-
string$encrypt The cipher name.
Returns
voidThrows
RuntimeExceptionWhen an invalid cipher is provided.
_decode() ¶ protected
_decode(string $value, string|false $encrypt, string|null $key): string|array
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_decrypt() ¶ protected
_decrypt(string[]|string $values, string|false $mode, string|null $key = null): string|array
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_encrypt() ¶ protected
_encrypt(string|array $value, string|false $encrypt, string|null $key = null): string
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_explode() ¶ protected
_explode(string $string): string|array
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_getBodyAsString() ¶ protected
_getBodyAsString(): string
Get the response body as string
Returns
string_getCookieEncryptionKey() ¶ protected
_getCookieEncryptionKey(): string
Returns the encryption key to be used.
Returns
string_handleError() ¶ protected
_handleError(Throwable $exception): void
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.
Returns
void_implode() ¶ protected
_implode(array $array): string
Implode method to keep keys are multidimensional arrays
Parameters
-
array$array Map of key and values
Returns
string_makeDispatcher() ¶ protected
_makeDispatcher(): Cake\TestSuite\MiddlewareDispatcher
Get the correct dispatcher instance.
Returns
Cake\TestSuite\MiddlewareDispatcher_sendRequest() ¶ protected
_sendRequest(string|array $url, string $method, string|array $data = []): void
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.
Returns
voidThrows
PHPUnit\Exception|Throwable_url() ¶ protected
_url(string $url): array
Creates a valid request url and parameter array more like Request::_url()
Parameters
-
string$url The URL
Returns
arrayassertContentType() ¶ public
assertContentType(string $type, string $message = ''): void
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.
Returns
voidassertCookie() ¶ public
assertCookie(mixed $expected, string $name, string $message = ''): void
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.
Returns
voidassertCookieEncrypted() ¶ public
assertCookieEncrypted(mixed $expected, string $name, string $encrypt = 'aes', string|null $key = null, string $message = ''): void
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.
Returns
voidSee Also
assertCookieNotSet() ¶ public
assertCookieNotSet(string $cookie, string $message = ''): void
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.
Returns
voidassertFileResponse() ¶ public
assertFileResponse(string $expected, string $message = ''): void
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.
Returns
voidassertFlashElement() ¶ public
assertFlashElement(string $expected, string $key = 'flash', string $message = ''): void
Asserts a flash element was set
Parameters
-
string$expected Expected element name
-
string$key optional Flash key
-
string$message optional Assertion failure message
Returns
voidassertFlashElementAt() ¶ public
assertFlashElementAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
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
Returns
voidassertFlashMessage() ¶ public
assertFlashMessage(string $expected, string $key = 'flash', string $message = ''): void
Asserts a flash message was set
Parameters
-
string$expected Expected message
-
string$key optional Flash key
-
string$message optional Assertion failure message
Returns
voidassertFlashMessageAt() ¶ public
assertFlashMessageAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
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
Returns
voidassertHeader() ¶ public
assertHeader(string $header, string $content, string $message = ''): void
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.
Returns
voidassertHeaderContains() ¶ public
assertHeaderContains(string $header, string $content, string $message = ''): void
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.
Returns
voidassertHeaderNotContains() ¶ public
assertHeaderNotContains(string $header, string $content, string $message = ''): void
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.
Returns
voidassertLayout() ¶ public
assertLayout(string $content, string $message = ''): void
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.
Returns
voidassertNoRedirect() ¶ public
assertNoRedirect(string $message = ''): void
Asserts that the Location header is not set.
Parameters
-
string$message optional The failure message that will be appended to the generated message.
Returns
voidassertRedirect() ¶ public
assertRedirect(string|array|null $url = null, string $message = ''): void
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.
Returns
voidassertRedirectContains() ¶ public
assertRedirectContains(string $url, string $message = ''): void
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.
Returns
voidassertRedirectEquals() ¶ public
assertRedirectEquals(string|array|null $url = null, string $message = ''): void
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.
Returns
voidassertRedirectNotContains() ¶ public
assertRedirectNotContains(string $url, string $message = ''): void
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.
Returns
voidassertResponseCode() ¶ public
assertResponseCode(int $code, string $message = ''): void
Asserts a specific response status code.
Parameters
-
int$code Status code to assert.
-
string$message optional Custom message for failure.
Returns
voidassertResponseContains() ¶ public
assertResponseContains(string $content, string $message = '', bool $ignoreCase = false): void
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.
Returns
voidassertResponseEmpty() ¶ public
assertResponseEmpty(string $message = ''): void
Assert response content is empty.
Parameters
-
string$message optional The failure message that will be appended to the generated message.
Returns
voidassertResponseEquals() ¶ public
assertResponseEquals(mixed $content, string $message = ''): void
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.
Returns
voidassertResponseError() ¶ public
assertResponseError(string $message = ''): void
Asserts that the response status code is in the 4xx range.
Parameters
-
string$message optional Custom message for failure.
Returns
voidassertResponseFailure() ¶ public
assertResponseFailure(string $message = ''): void
Asserts that the response status code is in the 5xx range.
Parameters
-
string$message optional Custom message for failure.
Returns
voidassertResponseNotContains() ¶ public
assertResponseNotContains(string $content, string $message = '', bool $ignoreCase = false): void
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.
Returns
voidassertResponseNotEmpty() ¶ public
assertResponseNotEmpty(string $message = ''): void
Assert response content is not empty.
Parameters
-
string$message optional The failure message that will be appended to the generated message.
Returns
voidassertResponseNotEquals() ¶ public
assertResponseNotEquals(mixed $content, string $message = ''): void
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.
Returns
voidassertResponseNotRegExp() ¶ public
assertResponseNotRegExp(string $pattern, string $message = ''): void
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.
Returns
voidassertResponseOk() ¶ public
assertResponseOk(string $message = ''): void
Asserts that the response status code is in the 2xx range.
Parameters
-
string$message optional Custom message for failure.
Returns
voidassertResponseRegExp() ¶ public
assertResponseRegExp(string $pattern, string $message = ''): void
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.
Returns
voidassertResponseSuccess() ¶ public
assertResponseSuccess(string $message = ''): void
Asserts that the response status code is in the 2xx/3xx range.
Parameters
-
string$message optional Custom message for failure.
Returns
voidassertSession() ¶ public
assertSession(mixed $expected, string $path, string $message = ''): void
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.
Returns
voidassertTemplate() ¶ public
assertTemplate(string $content, string $message = ''): void
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.
Returns
voidconfigApplication() ¶ public
configApplication(string $class, array|null $constructorArgs): void
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.
Returns
voidconfigRequest() ¶ public
configRequest(array $data): void
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.
Returns
voidcontrollerSpy() ¶ public
controllerSpy(Cake\Event\EventInterface $event, Cake\Controller\Controller|null $controller = null): void
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.
Returns
voidcookie() ¶ public
cookie(string $name, mixed $value): void
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.
Returns
voidcookieEncrypted() ¶ public
cookieEncrypted(string $name, mixed $value, string|false $encrypt = 'aes', string|null $key = null): void
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.
Returns
voidSee Also
delete() ¶ public
delete(string|array $url): void
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.
Returns
voiddisableErrorHandlerMiddleware() ¶ public
disableErrorHandlerMiddleware(): void
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.
Returns
voidenableCsrfToken() ¶ public
enableCsrfToken(): void
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.
Returns
voidenableRetainFlashMessages() ¶ public
enableRetainFlashMessages(): void
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
Returns
voidenableSecurityToken() ¶ public
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.
Returns
voidextractExceptionMessage() ¶ protected
extractExceptionMessage(Exception $exception): string
Extract verbose message for existing exception
Parameters
-
Exception$exception Exception to extract
Returns
stringextractVerboseMessage() ¶ protected
extractVerboseMessage(string $message): string
Inspect controller to extract possible causes of the failed assertion
Parameters
-
string$message Original message to use as a base
Returns
stringget() ¶ public
get(string|array $url): void
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.
Returns
voidgetSession() ¶ protected
getSession(): Cake\TestSuite\TestSession
Returns
Cake\TestSuite\TestSessionhead() ¶ public
head(string|array $url): void
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.
Returns
voidoptions() ¶ public
options(string|array $url): void
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.
Returns
voidpatch() ¶ public
patch(string|array $url, string|array $data = []): void
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.
Returns
voidpost() ¶ public
post(string|array $url, string|array $data = []): void
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.
Returns
voidput() ¶ public
put(string|array $url, string|array $data = []): void
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.
Returns
voidsession() ¶ public
session(array $data): void
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.
Returns
voidsetUnlockedFields() ¶ public
setUnlockedFields(string[] $unlockedFields = []): void
Set list of fields that are excluded from field validation.
Parameters
-
string[]$unlockedFields optional List of fields that are excluded from field validation.
Returns
voidviewVariable() ¶ public
viewVariable(string $name): mixed
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
mixedProperty Detail
$_csrfToken ¶ protected
Boolean flag for whether or not the request should have a CSRF token added.
Type
bool$_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