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.
array|null
The customized application constructor arguments.
string|null
The customized application class name.
Cake\Controller\Controller|null
The controller used in the last request.
array
Cookie data to use in the next request.
string|null
string
The name that will be used when retrieving the csrf token.
bool
Boolean flag for whether the request should have a CSRF token added.
Throwable|null
The exception being thrown if the case.
array
Stored flash messages before render
string
The last rendered layout
array
The data used to build the next request.
Cake\Http\Session
The session instance from the last request
Psr\Http\Message\ResponseInterface|null
The response for the most recent request.
bool
Boolean flag for whether the request should re-store flash messages
bool
Boolean flag for whether the request should have a SecurityComponent token added.
array
Session data to use in the next request.
array<string>
List of fields that are excluded from field validation.
array<string>
Valid cipher names for encrypted cookies.
string
The last rendered view
Add the CSRF and Security Component tokens if necessary.
Creates a request object with the configured options and parameters.
Recursively casts all data to string as that is how data would be POSTed in the real world
Helper method for validating encryption cipher names.
Decodes and decrypts a single value.
Decrypts $value using public $type method in Security class
Encrypts $value using public $type method in Security class
Explode method to return array from string set in CookieComponent::_implode() Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
Get the response body as string
Returns the encryption key to be used.
Attempts to render an error response for a given exception.
Implode method to keep keys are multidimensional arrays
Get the correct dispatcher instance.
Creates and send the request into a Dispatcher instance.
Creates a valid request url and parameter array more like Request::_url()
Asserts content type
Asserts cookie values
Asserts cookie values which are encrypted by the CookieComponent.
Asserts a cookie has not been set in the response
Asserts that a file with the given name was sent in the response
Asserts a flash element was set
Asserts a flash element was set at a certain index
Asserts a flash message was set
Asserts a flash message was set at a certain index
Asserts response headers
Asserts response header contains a string
Asserts response header does not contain a string
Asserts that the search string was in the layout name.
Asserts that the Location header is not set.
Asserts that the Location header is correct. Comparison is made against a full URL.
Asserts that the Location header contains a substring
Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
Asserts that the Location header does not contain a substring
Asserts a specific response status code.
Asserts content exists in the response body.
Assert response content is empty.
Asserts content in the response body equals.
Asserts that the response status code is in the 4xx range.
Asserts that the response status code is in the 5xx range.
Asserts content does not exist in the response body.
Assert response content is not empty.
Asserts content in the response body not equals.
Asserts that the response body does not match a given regular expression.
Asserts that the response status code is in the 2xx range.
Asserts that the response body matches a given regular expression.
Asserts that the response status code is in the 2xx/3xx range.
Asserts session contents
Asserts session key exists.
Asserts a session key does not exist.
Asserts that the search string was in the template name.
Clears the state used for requests.
Clears any mocks that were defined and cleans up application class configuration.
Configure the application class to use in integration tests.
Configures the data for the next request.
Adds additional event spies to the controller/view event manager.
Sets a request cookie for future requests.
Sets a encrypted request cookie for future requests.
Create an application instance.
Performs a DELETE request using the current request data.
Disable the error handler middleware.
Calling this method will add a CSRF token to the request.
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
Calling this method will enable a SecurityComponent compatible token to be added to request data. This lets you easily test actions protected by SecurityComponent.
Extract verbose message for existing exception
Inspect controller to extract possible causes of the failed assertion
Performs a GET request using the current request data.
Performs a HEAD request using the current request data.
Add a mocked service to the container.
Wrap the application's container with one containing mocks.
Performs an OPTIONS request using the current request data.
Performs a PATCH request using the current request data.
Performs a POST request using the current request data.
Performs a PUT request using the current request data.
Remove a mocked service to the container.
Sets session data.
Set list of fields that are excluded from field validation.
Fetches a view variable by name.
_addTokens(string $url, array $data): array
Add the CSRF and Security Component tokens if necessary.
string
$url The URL the form is being submitted on.
array
$data The request body data.
array
_buildRequest(string $url, string $method, array|string $data = []): array
Creates a request object with the configured options and parameters.
string
$url The URL
string
$method The HTTP method
array|string
$data optional The request data.
array
_castToString(array $data): array
Recursively casts all data to string as that is how data would be POSTed in the real world
array
$data POST data
array
_checkCipher(string $encrypt): void
Helper method for validating encryption cipher names.
string
$encrypt The cipher name.
void
RuntimeException
_decode(string $value, string|false $encrypt, string|null $key): array|string
Decodes and decrypts a single value.
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.
array|string
_decrypt(array<string>|string $values, string|false $mode, string|null $key = null): array|string
Decrypts $value using public $type method in Security class
array<string>|string
$values Values to decrypt
string|false
$mode Encryption mode
string|null
$key optional Used as the security salt if specified.
array|string
_encrypt(array|string $value, string|false $encrypt, string|null $key = null): string
Encrypts $value using public $type method in Security class
array|string
$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.
string
_explode(string $string): array|string
Explode method to return array from string set in CookieComponent::_implode() Maintains reading backwards compatibility with 1.x CookieComponent::_implode().
string
$string A string containing JSON encoded data, or a bare string.
array|string
_getBodyAsString(): string
Get the response body as string
string
_getCookieEncryptionKey(): string
Returns the encryption key to be used.
string
_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.
Throwable
$exception Exception to handle.
void
_implode(array $array): string
Implode method to keep keys are multidimensional arrays
array
$array Map of key and values
string
_makeDispatcher(): Cake\TestSuite\MiddlewareDispatcher
Get the correct dispatcher instance.
Cake\TestSuite\MiddlewareDispatcher
_sendRequest(array|string $url, string $method, array|string $data = []): void
Creates and send the request into a Dispatcher instance.
Receives and stores the response for future inspection.
array|string
$url The URL
string
$method The HTTP method
array|string
$data optional The request data.
void
PHPUnit\ExceptionThrowable
_url(string $url): array
Creates a valid request url and parameter array more like Request::_url()
string
$url The URL
array
assertContentType(string $type, string $message = ''): void
Asserts content type
string
$type The content-type to check for.
string
$message optional The failure message that will be appended to the generated message.
void
assertCookie(mixed $expected, string $name, string $message = ''): void
Asserts cookie values
mixed
$expected The expected contents.
string
$name The cookie name.
string
$message optional The failure message that will be appended to the generated message.
void
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.
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.
void
assertCookieNotSet(string $cookie, string $message = ''): void
Asserts a cookie has not been set in the response
string
$cookie The cookie name to check
string
$message optional The failure message that will be appended to the generated message.
void
assertFileResponse(string $expected, string $message = ''): void
Asserts that a file with the given name was sent in the response
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.
void
assertFlashElement(string $expected, string $key = 'flash', string $message = ''): void
Asserts a flash element was set
string
$expected Expected element name
string
$key optional Flash key
string
$message optional Assertion failure message
void
assertFlashElementAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
Asserts a flash element was set at a certain index
int
$at Flash index
string
$expected Expected element name
string
$key optional Flash key
string
$message optional Assertion failure message
void
assertFlashMessage(string $expected, string $key = 'flash', string $message = ''): void
Asserts a flash message was set
string
$expected Expected message
string
$key optional Flash key
string
$message optional Assertion failure message
void
assertFlashMessageAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
Asserts a flash message was set at a certain index
int
$at Flash index
string
$expected Expected message
string
$key optional Flash key
string
$message optional Assertion failure message
void
assertHeader(string $header, string $content, string $message = ''): void
Asserts response headers
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.
void
assertHeaderContains(string $header, string $content, string $message = ''): void
Asserts response header contains a string
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.
void
assertHeaderNotContains(string $header, string $content, string $message = ''): void
Asserts response header does not contain a string
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.
void
assertLayout(string $content, string $message = ''): void
Asserts that the search string was in the layout name.
string
$content The content to check for.
string
$message optional The failure message that will be appended to the generated message.
void
assertNoRedirect(string $message = ''): void
Asserts that the Location header is not set.
string
$message optional The failure message that will be appended to the generated message.
void
assertRedirect(array|string|null $url = null, string $message = ''): void
Asserts that the Location header is correct. Comparison is made against a full URL.
array|string|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.
void
assertRedirectContains(string $url, string $message = ''): void
Asserts that the Location header contains a substring
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.
void
assertRedirectEquals(array|string|null $url = null, string $message = ''): void
Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
array|string|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.
void
assertRedirectNotContains(string $url, string $message = ''): void
Asserts that the Location header does not contain a substring
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.
void
assertResponseCode(int $code, string $message = ''): void
Asserts a specific response status code.
int
$code Status code to assert.
string
$message optional Custom message for failure.
void
assertResponseContains(string $content, string $message = '', bool $ignoreCase = false): void
Asserts content exists in the response body.
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.
void
assertResponseEmpty(string $message = ''): void
Assert response content is empty.
string
$message optional The failure message that will be appended to the generated message.
void
assertResponseEquals(mixed $content, string $message = ''): void
Asserts content in the response body equals.
mixed
$content The content to check for.
string
$message optional The failure message that will be appended to the generated message.
void
assertResponseError(string $message = ''): void
Asserts that the response status code is in the 4xx range.
string
$message optional Custom message for failure.
void
assertResponseFailure(string $message = ''): void
Asserts that the response status code is in the 5xx range.
string
$message optional Custom message for failure.
void
assertResponseNotContains(string $content, string $message = '', bool $ignoreCase = false): void
Asserts content does not exist in the response body.
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.
void
assertResponseNotEmpty(string $message = ''): void
Assert response content is not empty.
string
$message optional The failure message that will be appended to the generated message.
void
assertResponseNotEquals(mixed $content, string $message = ''): void
Asserts content in the response body not equals.
mixed
$content The content to check for.
string
$message optional The failure message that will be appended to the generated message.
void
assertResponseNotRegExp(string $pattern, string $message = ''): void
Asserts that the response body does not match a given regular expression.
string
$pattern The pattern to compare against.
string
$message optional The failure message that will be appended to the generated message.
void
assertResponseOk(string $message = ''): void
Asserts that the response status code is in the 2xx range.
string
$message optional Custom message for failure.
void
assertResponseRegExp(string $pattern, string $message = ''): void
Asserts that the response body matches a given regular expression.
string
$pattern The pattern to compare against.
string
$message optional The failure message that will be appended to the generated message.
void
assertResponseSuccess(string $message = ''): void
Asserts that the response status code is in the 2xx/3xx range.
string
$message optional Custom message for failure.
void
assertSession(mixed $expected, string $path, string $message = ''): void
Asserts session contents
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.
void
assertSessionHasKey(string $path, string $message = ''): void
Asserts session key exists.
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.
void
assertSessionNotHasKey(string $path, string $message = ''): void
Asserts a session key does not exist.
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.
void
assertTemplate(string $content, string $message = ''): void
Asserts that the search string was in the template name.
string
$content The content to check for.
string
$message optional The failure message that will be appended to the generated message.
void
cleanup(): void
Clears the state used for requests.
void
cleanupContainer(): void
Clears any mocks that were defined and cleans up application class configuration.
void
configApplication(string $class, array|null $constructorArgs): void
Configure the application class to use in integration tests.
string
$class The application class name.
array|null
$constructorArgs The constructor arguments for your application class.
void
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. Sub-keys like 'headers' will be reset, though.
array
$data The request data to use.
void
controllerSpy(Cake\Event\EventInterface $event, Cake\Controller\Controller|null $controller = null): void
Adds additional event spies to the controller/view event manager.
Cake\Event\EventInterface
$event A dispatcher event.
Cake\Controller\Controller|null
$controller optional Controller instance.
void
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.
string
$name The cookie name to use.
mixed
$value The value of the cookie.
void
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.
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.
void
createApp(): Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface
Create an application instance.
Uses the configuration set in configApplication()
.
Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface
delete(array|string $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.
array|string
$url The URL to request.
void
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.
void
enableCsrfToken(string $cookieName = 'csrfToken'): 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.
string
$cookieName optional The name of the csrf token cookie.
void
enableRetainFlashMessages(): void
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
void
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.
void
extractExceptionMessage(Exception $exception): string
Extract verbose message for existing exception
Exception
$exception Exception to extract
string
extractVerboseMessage(string $message): string
Inspect controller to extract possible causes of the failed assertion
string
$message Original message to use as a base
string
get(array|string $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.
array|string
$url The URL to request.
void
getSession(): Cake\TestSuite\TestSession
Cake\TestSuite\TestSession
head(array|string $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.
array|string
$url The URL to request.
void
mockService(string $class, Closure $factory): $this
Add a mocked service to the container.
When the container is created the provided classname will be mapped to the factory function. The factory function will be used to create mocked services.
string
$class The class or interface you want to define.
Closure
$factory The factory function for mocked services.
$this
modifyContainer(Cake\Event\EventInterface $event, Cake\Core\ContainerInterface $container): Cake\Core\ContainerInterface|null
Wrap the application's container with one containing mocks.
If any mocked services are defined, the application's container will be replaced with one containing mocks. The original container will be set as a delegate to the mock container.
Cake\Event\EventInterface
$event The event
Cake\Core\ContainerInterface
$container The container to wrap.
Cake\Core\ContainerInterface|null
options(array|string $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.
array|string
$url The URL to request.
void
patch(array|string $url, array|string $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.
array|string
$url The URL to request.
array|string
$data optional The data for the request.
void
post(array|string $url, array|string $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.
array|string
$url The URL to request.
array|string
$data optional The data for the request.
void
put(array|string $url, array|string $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.
array|string
$url The URL to request.
array|string
$data optional The data for the request.
void
removeMockService(string $class): $this
Remove a mocked service to the container.
string
$class The class or interface you want to remove.
$this
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.
array
$data The session data to use.
void
setUnlockedFields(array<string> $unlockedFields = []): void
Set list of fields that are excluded from field validation.
array<string>
$unlockedFields optional List of fields that are excluded from field validation.
void
viewVariable(string $name): mixed
Fetches a view variable by name.
If the view variable does not exist, null will be returned.
string
$name The view variable to get.
mixed
The customized application constructor arguments.
array|null
The customized application class name.
string|null
The controller used in the last request.
Cake\Controller\Controller|null
Cookie data to use in the next request.
array
string|null
The name that will be used when retrieving the csrf token.
string
Boolean flag for whether the request should have a CSRF token added.
bool
The exception being thrown if the case.
Throwable|null
Stored flash messages before render
array
The last rendered layout
string
The data used to build the next request.
array
The session instance from the last request
Cake\Http\Session
The response for the most recent request.
Psr\Http\Message\ResponseInterface|null
Boolean flag for whether the request should re-store flash messages
bool
Boolean flag for whether the request should have a SecurityComponent token added.
bool
Session data to use in the next request.
array
List of fields that are excluded from field validation.
array<string>
Valid cipher names for encrypted cookies.
array<string>
The last rendered view
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.4/trait-Cake.TestSuite.IntegrationTestTrait.html