PHPUnit test setup with Silex in Ubuntu
I am assuming that you already have silex installed by composer. To install phpunit through composer, add the following line at require-dev options
[ ] Add a line to your composer.json - "phpunit/phpunit": "4.3.*"
[ ] Run composer update Done. You will see the phpunit file inside /vendor/bin directory. You can make a symlink to this phpunit to /usr/bin and add chmod +x phpunit.
Then verify by executing phpunit In my case, I have created a service provider and I will test that. I've created a src directory beside web.
The folder structure is
-web
-src
-- ExampleProject
--- Provider
----MongoServiceProvider
-vendor
Create 'tests' directory beside src directory. Follow the same directory hierarchy like src. Create a Test script.
namespace Tests\Provider; use Silex\Application; use ExampleProject\Provider\MongoServiceProvider; class MongoServiceProviderTest extends \PHPUnit_Framework_TestCase { public function testRegister() { $app = new Application(); $app->register(new MongoServiceProvider()); $conn = $app['mongo_service']; $this->assertInstanceOf('ExampleProject\Provider\MongoServiceProvider', $conn); } /** * @depends testRegister * @dataProvider createDataProvider */ public function testCreate($type, $json) { $app = new Application(); $app->register(new MongoServiceProvider()); $app['mongo_client'] = $app->share(function () { return new \MongoClient(); }); $conn = $app['mongo_service']; $conn->create($type, $json); $json_object = json_decode($json); $collection = $app['mongo_client']->selectCollection( $app['mongo_service']::DB_NAME, $type); $document = $collection->findOne($json_object); $this->assertEquals($document['x'], 'y'); } public function createDataProvider(){ return array( array('hello', '{"x" : "y"}') ); } }Now execute: phpunit /path/to/test/file Ex: phpunit /tests/ExampleProject/Provider/ It will test all the test cases inside this directory.
Leave a comment