This is a port of the VCR Ruby library to PHP.
Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests. A bit of documentation can be found on the php-vcr website.
Disclaimer: Doing this in PHP is not as easy as in programming languages which support monkey patching (I'm looking at you, Ruby)
$http_response_header
see #96)VCRVCR::turnOn();
in your tests/bootstrap.php
VCRVCR::turnOn();
in your tests/bootstrap.php
Using static method calls:
class VCRTest extends TestCase
{
public function testShouldInterceptStreamWrapper()
{
// After turning on the VCR will intercept all requests
VCRVCR::turnOn();
// Record requests and responses in cassette file 'example'
VCRVCR::insertCassette('example');
// Following request will be recorded once and replayed in future test runs
$result = file_get_contents('http://example.com');
$this->assertNotEmpty($result);
// To stop recording requests, eject the cassette
VCRVCR::eject();
// Turn off VCR to stop intercepting requests
VCRVCR::turnOff();
}
public function testShouldThrowExceptionIfNoCasettePresent()
{
$this->setExpectedException(
'BadMethodCallException',
"Invalid http request. No cassette inserted. Please make sure to insert "
. "a cassette in your unit test using VCR::insertCassette('name');"
);
VCRVCR::turnOn();
// If there is no cassette inserted, a request throws an exception
file_get_contents('http://example.com');
}
}
You can use annotations in PHPUnit by using phpunit-testlistener-vcr:
class VCRTest extends TestCase
{
/**
* @vcr unittest_annotation_test
*/
public function testInterceptsWithAnnotations()
{
// Requests are intercepted and stored into tests/fixtures/unittest_annotation_test.
$result = file_get_contents('http://google.com');
$this->assertEquals('This is a annotation test dummy.', $result, 'Call was not intercepted (using annotations).');
// VCR is automatically turned on and off.
}
}
Simply run the following command:
$ composer require --dev php-vcr/php-vcr
PHP-VCR depends on:
Composer installs all dependencies except extensions like curl.
In order to run all tests you need to get development dependencies using composer:
composer install
composer test
The changelog has moved to the PHP-VCR releases page.
Old changelog entries
Copyright (c) 2013-2023 Adrian Philipp. Released under the terms of the MIT license. See LICENSE for details. Contributors