PHP quick fixture data for phpunit testing

Posted: 2014-11-20 01:35:02

You can use VCR or other libraries to make fixture data. But sometimes you can just make the request and save the results using this technique. From then on you mock and return the data.

Get the data.

In this example I had a Client that would get data and return it for import. I was testing out the class that would take this data and import it and do other things. So I make my phpunit test methods of that class (not the Client it is fully tested)


/** * @test */ public function should_get_data_to_import() { //Load up the client I will later mock, but to get some data to mock $client = new Client(); //Get the results (api return json) $results = $client->getData(); //Get the yaml library I am using to covert it to Yaml $yaml = new Yaml(); //Convert it to Yaml from Array $results_yml = $yaml->dump($results); //Save it for now file_put_contents('/tmp/data.yml', $results_yml); }

Once that is done I copy that data.yml file to fixtures/data.yml which is in the tests folder. Here is a quick look at the folders.

tests
tests/fixtures
// @NOTE this is the file we are using for the test example above
tests/NameSpace/Tests/ClassTest.php 

Finally I rewrite that same test method as

/**
 * @test
 */
public function should_get_data_to_import()
{
   $yaml = new Yaml();
   $fixture = $yaml->parse(__DIR__ . '/../fixtures/data.yml');
   $client = m::mock();
   $client->shouldReceive('getData')->andReturn($fixture);
   $classTesting new ClassTest($client); //we inject the mock into it
   $classTesting->importData();

   $this->assertCount(100, $classTesting->getDataImported()); 
}

The client in this case if a fully tested standalone client so I am not testing it. Just my use of it to migrate data.