Thursday, February 26, 2015

Use of Apigility to Create REST/RPC APIs

Hi,

Apigility is an API Builder, designed to simplify creating and maintaining useful, easy to consume, and well structured APIs. 
You can use Apigility in any PHP application, using all the libraries and frameworks that you want.
Apigility offers the ability to generate API documentation and Create REST/RPC API using the Admin UI i.e. easy to use and fast to implement. 

Step-by-Step Guide

System Requirements
Need PHP version 5.3.23 or greater
Please follow the steps for installation from the given link below where you can find your taste of installation i.e
Via Console, Tarball, GIT, Composer etc..
https://apigility.org/documentation/intro/installation

Authentication & Authorization:
Apigility takes a lightweight, layered, and extensible approach to solving both problems of authentication and authorization. Apigility delivers three methods to authenticate identities: HTTP Basic authentication, HTTP Digest authentication, and OAuth2 (by way of Brent Shaffer's PHP OAuth2 package). 

Out of 3 authentications, OAuth2 is bit tough to implement in your application.
OAuth2 is an authentication framework used worldwide; for instance Facebook Github, and Twitter use this protocol to authenticate their APIs. The OAuth2 protocol is actually a framework for authorization. From the abstract of RFC 6749 you can read that.
The use cases covered by the OAuth2 framework are:
  • Web-server applications
  • Browser-based applications
  • Mobile apps
  • Username and password access
  • Application access
You can configure the OAuth2 authentication via OAuth2 sql which is provided inside the Apigilty Library. Please follow the below Link to configure it.
 https://apigility.org/documentation/auth/authentication-oauth2

Create Your REST API inside Apigility, please follow the below Url:
https://apigility.org/documentation/intro/getting-started
https://apigility.org/documentation/content-validation/intro

For API Documentation also Apigility helps you a lot. While creation of API, you can define the documentation of the respected API. For further Information how to create it please follow the below URL:
https://apigility.org/documentation/api-doc/intro



For further knowledge on Apigilty:
https://apigility.org/documentation

Wednesday, October 29, 2014

GIT : Branching

Hi,

Git Branching is the basic need in Git Version control.

Here i like to share the steps to manage the branch in your application repository.

Step 1: I am assuming initially you have "master" branch in your application then you create another branch i.e. "development" then run the below command:


# git branch development


# git checkout development  

//it will switch the branch into "development" branch

Step 2: Now your are in fresh "development" branch. Then push your "master" branch code into the "development" branch.

# git push origin development

GIT clone form specific branch

# git clone <git-repo-url> -b <branch-name> --single-branch

Ex:
Suppose i had to take git clone of specific branch like development-fix not all others then my command would be

# git clone git@bitbucket.org:project/project-name.git -b development-fix --single-branch






  

Wednesday, October 15, 2014

Linux: How to compare multiple files in given directories

Hi,

In linux, any flavor you are using, you can find out the file's content differences in two directory.

For example :
You have directory "test1" and "test2" both contains the multiple files and directory.

And your problem is to find out files where content are mismatch with the "test1" directory's file.

So, do not worry about this. Linux provide a very powerful tool to find out the differences i.e diff command:



# diff -qrs test1/ test2/ 

Where,
-q : report only when files differ
-r : recursively compare any subdirectories found
-s : report when two files are the same

Above command will give you output in report format where files content differ or identical.

If you found something differ in your file in the final report, then you can run the below command to see the actual differences.


# diff test1/file1 test2/file1





Tuesday, September 23, 2014

NodeJs mongoDB : With sample application

Hi,

NodeJs connectivity with the MongoDB Database.
Here, i am assuming that you have NodeJS, NPM and socket.io installed on your machine. If not kindly follow the below URL to install the above tools:
http://tarunlinux.blogspot.in/2014/09/nodejs-basics.html

Lets start to create sample appication on NodeJs with mongoDB connectivity.

Step 1: Install mongoDB on your machine... Please follow the below link to setup mongoDB..
http://tarunlinux.blogspot.in/2014/09/mongodb-basics.html

Step 2: Install NodeJS mongoDB dependency with the below command:

1
# sudo npm install mongodb



It will install mongodb module in your application.

Step 3: Create server.js file for the nodejs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var mongo = require('mongodb').MongoClient;
var client = require('socket.io').listen(8080).sockets;  //Load socket.io module

mongo.connect('mongodb://localhost/tarundb', function(err, db){
    client.on('connection', function(socket){
        var col = db.collection('employee'); //connect with collection of tarundb

        //Insert data into mongodb
        col.insert({name: 'Tarun', age:26}, function() {
            console.log("Inserted");
        });
        
        //emit all the records
        col.find().limit(100).toArray(function(err, res){
            if(err) throw err;
            
            socket.emit('all-data', res);
        });
    });
});


Step 4: Create Index.html file for the frontend:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
    <head>
        <title> NodeJs MongoDB APP </title>
    </head>
    <body>
        <div class="data-set"></div>
        <script src="http://localhost:8080/socket.io/socket.io.js" type="text/javascript"></script>
        <script src="http://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
        <script>
        (function(){
            try{
                var socket = io.connect('http://localhost:8080');
            } catch(e){
                console.log(e);
            }
            
            if(socket !== undefined) {
                socket.on('all-data', function(data){
                    for(var i=0; i < data.length; i++) {
                        $(".data-set").append('<li>'+ data[i].name +'</li>');
                    }
                });
            }
        })();
        </script>
    </body>
</html>


Step 5: Now you have to run server.js file
# nodejs server.js

Then open your browser, with url: http://localhost:8080/
Where you will see the mongoDB connectivity and their data.

I hope it will help you for NodeJs Connectivity with MongoDB.. If you have any query, please put your comments, i highly appreciate that ...

Bye..

Monday, September 22, 2014

NodeJS MySql Connectivity : With Sample Application

Hi,

Here, i will share with you on NodeJS sample application with MySql Database connectivity.

I am assuming that  you already installed the NodeJS, NPM and Socket.io on your machine.
If not, you can follow below link to install the above requirements
http://tarunlinux.blogspot.in/2014/09/nodejs-basics.html

Here, I will show you in step-wise :

Step 1: Install the mysql module... here also i am assuming that mysql is already installed in your machine.
Now install mysql module for the NodeJs dependency.
# sudo npm install mysql

That will install the MySql dependency in your machine.

Step 2: Now Create the server.js file for the nodejs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var mysql = require('mysql'); // load mysql module
var client = require('socket.io').listen(8080).sockets;  //Load socket.io module

//Database connectivity
var db = mysql.createConnection({
    host: 'localhost'
    , user: 'root'
    , password: 'root'
    , database: 'zfskel'
    , port: '3306'    
});

db.connect(function(err){
    console.log(err);
});

//Create connection with the client and emit data on socket
client.on('connection', function(socket){
    db.query('SELECT * FROM employee')
      .on('result', function(data){

        socket.emit('all-data', [data]);
    });
});


Step 3: Create Index.html file for the front-end:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
    <head>
        <title> NodeJs Mysql APP </title>
        <link rel="stylesheet" href="">
    </head>
    <body>
        <div class="data-set"></div>
    <script src="http://localhost:8080/socket.io/socket.io.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <script>
    (function(){
        try{
            var socket = io.connect('http://localhost:8080');
        } catch(e){
            console.log(e);
        }
        
        if(socket !== undefined) {
            socket.on('all-data', function(data){
                for(var i=0; i < data.length; i++) {
                    $(".data-set").append('<li>'+ data[i].name +'</li>');
                }
            });
        }
    })();
    </script>
    </body>
</html>



Now your have 2 files i.e. server.js and index.html file.

Step 4: Now you need the sql file for the database connectivity:

1
2
3
4
5
6
7
CREATE TABLE `employee` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `employee` VALUES (1,'tarun',26),(2,'varun',34);


Step 5: Now you have to run only server.js file form command line:
# nodejs server.js

Then open your browser and run the below url:
http://localhost:8080/

Here, you will see the MySql data on your browser...

I hope it will help you to understand NodeJs and its connectivity with the MySql connectivity.

Bye.. :)

NodeJS Basics

Hi,

I like to share some information on NodeJs.

What is NodeJs.
NodeJs is a cross-platform runtime environment for server-side and networking applications.
Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows and Linux with no changes.
Node.js internally uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. 

In this section, I will tell you on the below points:
1. How to install NodeJs
2. How to install NPM
3. How to install Socket.io
4. How to run nodejs from CLI

1) Installation:
I install the NodeJs on Ubuntu 14.04 O.S with the below command:

# sudo apt-get install nodejs

2) Install NPM(Node Package Manager):

# sudo apt-get install npm

Here, NPM basically a package manager.
NPM is helpful to maintain the NodeJS  dependency in your development.

3) Install Socket.io
Basically it is useful to maintain the socket connection with your frontend and backend. Or you can say..
Its provide you a real time communication between your node.js server and clients.
Installation command:
# sudo npm install socket.io

4) Run the NodeJs:
Applications are executed from the command line with the command:

# nodejs <application name>.js

In my next article, i will demonstrate your how to use it in real time communication.

Thursday, September 18, 2014

mongoDB Basics

Hi,

From last few days i started on mongoDB. It looks interesting as i never work on noSQL type database. Before that i worked on SQL, MySQL and Oracle Database.

mongoDB is the different one from the above DBs. Here, i like to share with you a quick intro on mongoDB.

mongoDB: is a cross-platform document-oriented database.
Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON)
making the integration of data in certain types of applications easier and faster.

I use the mongoDB in one of my project... I installed this on my machine Whose OS is Ubuntu 14.04 version.

Installation
# apt-get install mongodb
It will install the client and server and other library associated to it.

Open the port in mongod.conf,
# sudo vi /etc/mongodb.conf
Just uncomment the below line in conf file
port = 27017

Start of mongoDB
# sudo service mongodb start

Its a pretty simple to setup on Ubuntu... :)

mongo is a part of the standard mongoDB distribution and provides a full JavaScript environment with complete access to the JavaScript language and all standard functions as well as a full database interface for mongoDB.

Now Start the mongo
# mongo
It will take you on mongo prompt....

Some basic commands for mongoDB

> db  // show current db

> show dbs //show all db with their size

> use db-name  //shitch to your selected db

> help  //show help for the mongodb

> show collections //show the collections used in your selected db

> db.collection-name.find()  // give you all records in your collection

> db.collection-name.insert({name:'Tarun', message:'Welcome'})  //insert record into the collection

> db.collection-name.find({name:'Tarun'})  //give the particular record from your collection
Here, important point is, this is case-sensitive.
if your search as
> db.collection-name.find({name:'tarun'})  // it will not show records whose name as Tarun  

> db.collection-name.findOne()  //to get the one document from the collection
 
> db.collection-name.find().limit(3)  // to get 3 document from all document


Thursday, September 11, 2014

Docker : Container Technology

Hi,

This is on the new technology that i listened from someone and that makes some curiosity inside me.

After some search and digging on Google then i found some basic informations. Those information that i want to share with all blogger readers guys.

First is, What is Docker?
Why its required?
Why it's different from VM?
Then How can i use it in my activity?

Huuuu... Many questions..... :)

Lets start to know each and every question with their some basic information...

Now, Question 1: What is Docker?
Ans: Docker is basically a new container technology where developers or admin team can manage the application component with their desired versions in one place that says as container, after that they are able to ship that container at any place or say any machine without affecting machines configurations.

Or in Nutshell
providing an additional layer of abstraction and automation of operating system–level virtualization.

Question 2:  Why its required?
Ans: I thing previous ans is self explanatory for this one.
In further, With Docker, developers can build any app in any language using any tool chain. “Dockerized” apps are completely portable and can run anywhere.

Question 3:  Why it's different from VM(Virtual Machine)?
Ans:  
Virtual Machine: Each virtualized application includes not only the application - which may be only 10s of MB - and the necessary binaries and libraries, but also an entire guest operating system - which may weigh 10s of GB.

Docker: The Docker Engine container comprises just the application and its dependencies. It runs as an isolated process in userspace on the host operating system, sharing the kernel with other containers. Thus, it enjoys the resource isolation and allocation benefits of VMs but is much more portable and efficient.

Question: Then How can i use it in my activity?
Ans: I try to put some basic information on:
How to install it on your machine?
What are the basic command to use the docker?


INSTALLATION Process

Installation of the Docker in ubuntu 14.04 :

# sudo apt-get update

# sudo apt-get install docker.io

# sudo ln -sf /usr/bin/docker.io /usr/local/bin/docker

# sudo sed -i '$acomplete -F _docker docker' /etc/bash_completion.d/docker.io

# sudo docker run -i -t ubuntu /bin/bash

Above command will take you in bash prompt, where you can install the software/application that you want in the container.

Update the container package list:
# apt-get update
# apt-get install apache2   // install the apache2 in your container
# apt-get install mysql-server mysql-client
//install the mysql-server and mysql-client

# apt-get install php5 php5-mysql libapache2-mod-php5
// install php on the container

To exit from the docker:
# exit 
//It will take out you from docker prompt.

If you want to have particular distribution then use:
# docker run -i -t ubuntu:12.04 /bin/bash
It will create the ubuntu12.04 container.



Basic Command to get the docker information:

1. To know the docker version
# docker version

2. To search the specific docker image
docker search <image-name>
EX:
# docker search tutorial

3. To download the docker specific container image
docker pull <username>/<repo-name>
EX:
# docker pull tarunsinghal/lampstack

4. To run the docker container with the some output
docker run <username>/<repo-name> echo "Hello Tarun"
EX:
# docker run tarunsinghal/lampstack echo "Hello Tarun"

5. To run the any install in docker container
docker run <username>/<repo-name> apt-get install -y ping
EX:
# docker run tarunsinghal/lampstack apt-get install -y ping

6. To commit the docker images changes
docker commit <id> <username>/<repo-name>
EX:
# docker  commit 6789 tarunsinghal/lampstack 

Here,  id: is the docker id which will be identified by the
# docker ps -a   // that shows you number of container with their ids.
if you pass ids starting 4 character then thats enough to identify the right container.

7. To run the docker installed utility
docker run <username>/<repo-name> ping google.com
EX:
# docker run tarunsinghal/lampstack ping google.com

8. To know the running docker information with specific id.
# docker ps -a  // will tell you the running docker(s)
# docker inspect <id-number>  // will give you complete information on this docker ids

here, id : is the docker container id number

9. To push the new image in the docker registry
# docker push <username>/<repo-name>

In this way, you downloaded the docker with given repo, after that you make some changes and push it again to the docker registry with new name.

Now, that new docker images will be usable in any other similar environment.

10. If you want docker will automatically on when you boot your machine
# docker chkconfig docker on

Further more, if you want to know on this you can refer the below URL for Docker:  https://www.docker.com

Wednesday, September 3, 2014

PHPUnit Pear Install In Ubuntu

Hi,

To install the PHPUnit in ubuntu, Please follow the below instruction:

If your system does not have Pear installed then:

# sudo apt-get install php-pear

# sudo pear channel-update pear.php.net

Now, You have to install the PHPUnit, with the help of pear easily:


# sudo pear channel-discover pear.phpunit.de

# sudo pear install -a phpunit/PHPUnit

If you want the code-coverage analysis of your application then you have to install the PHP extension i.e. Xdebug , That will help you create the html formatted report where you can see:
i) Code coverage percentage
ii) Which test case run on your application code

Command, to install Xdebug:
# sudo apt-get install php5-xdebug

NOTE: The above process of installation via PEAR would be outdated on Dec, 2014.
Please try to use Composer instead of PEAR





Thursday, August 28, 2014

PHPUnit in Zend Framework 2

Hi,

Process of setup PHPUnit testing in Zend Framework-2:

NOTE: Before starting to describe the process of PHPUnit i assuming that readers are aware of Zend Framework-2.

Step 1: PHPUnit Installation with the help of "Pear"
# pear config-set auto_discover 1
# pear install pear.phpunit.de/PHPUnit

Step 2: Create "test" directory inside your module.

Step 3: create phpunit.xml, TestConfig.php and Bootstrap.php file inside the "test" directory.

phpunit.xml File
<?xml version="1.0" encoding="UTF-8"?> 
<phpunit bootstrap="Bootstrap.php">
 <php>
  <!--server name="SERVER_PORT" value="80"/ -->
   </php>
    <testsuites>
        <testsuite name="Demo PHPUnit">
            <directory>./ApplicationTest</directory>
        </testsuite>
    </testsuites>
</phpunit>

TestConfig.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
return array(
    'modules' => array(
        // Other modules needed
        'Application',
    ),
    'module_listener_options'   => array(
        'config_glob_paths' => array(
            '../../../config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths'      => array(
            'module',
            'vendor',
        ),
    ),
);


Bootstrap.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace ApplicationTest; // our namespace
 
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use RuntimeException;
use Zend\Session\Container;
 
error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);
 
class Bootstrap
{
    protected static $serviceManager;
    protected static $config;
    protected static $bootstrap;
 
    public static function init()
    {
        // Load the user-defined test configuration file, if it exists; otherwise, load
        if (is_readable(__DIR__ . '/TestConfig.php')) {
            $testConfig = include __DIR__ . '/TestConfig.php';
        } else {
            $testConfig = include __DIR__ . '/TestConfig.php.dist';
        }
 
        $zf2ModulePaths = array();
 
        if (isset($testConfig['module_listener_options']['module_paths'])) {
            $modulePaths = $testConfig['module_listener_options']['module_paths'];
            foreach ($modulePaths as $modulePath) {
                if (($path = static::findParentPath($modulePath)) ) {
                    $zf2ModulePaths[] = $path;
                }
            }
        }
         
        $zf2ModulePaths  = implode(PATH_SEPARATOR, $zf2ModulePaths) . PATH_SEPARATOR;
        $zf2ModulePaths .= getenv('ZF2_MODULES_TEST_PATHS') ?: (defined('ZF2_MODULES_TEST_PATHS') ? ZF2_MODULES_TEST_PATHS : '');
 
        static::initAutoloader();
 
        // use ModuleManager to load this module and it's dependencies
        $baseConfig = array(
            'module_listener_options' => array(
                'module_paths' => explode(PATH_SEPARATOR, $zf2ModulePaths),
            ),
        );
 
        $config = ArrayUtils::merge($baseConfig, $testConfig);
 
        $serviceManager = new ServiceManager(new ServiceManagerConfig());
        $serviceManager->setService('ApplicationConfig', $config);
        $serviceManager->get('ModuleManager')->loadModules();
 
        static::$serviceManager = $serviceManager;
        static::$config = $config;
    }
 
    public static function getServiceManager()
    {      
        return static::$serviceManager;
    }
 
    public static function getConfig()
    {
        
        return static::$config;
    }
 
    protected static function initAutoloader()
    {
        $vendorPath = static::findParentPath('vendor');
 
        if (is_readable($vendorPath . '/autoload.php')) {
            $loader = include $vendorPath . '/autoload.php';
        } else {
            $zf2Path = getenv('ZF2_PATH') ?: (defined('ZF2_PATH') ? ZF2_PATH : (is_dir($vendorPath . '/ZF2/library') ? $vendorPath . '/ZF2/library' : false));
 
            if (!$zf2Path) {
                throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
            }
 
            include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
 
        }
        
        AutoloaderFactory::factory(array(
            'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true,
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
                ),
            ),
        ));
    }
 
    protected static function findParentPath($path)
    {
        $dir = __DIR__;
        $previousDir = '.';
        while (!is_dir($dir . '/' . $path)) {
            $dir = dirname($dir);
            if ($previousDir === $dir) return false;
            $previousDir = $dir;
        }
        return $dir . '/' . $path;
    }
}
 
Bootstrap::init();



Step 4: Create directory for module testing inside the "test" directory. Name should be same as the module name.
EX: if your module name is "Report" then your testing module-name would be "ReportTest"

Step 5: Create Controller directory whose name would be "Controller" inside the Test module i.e. "ReportTest"

Step 6: Create controller class file inside your controller dir, named as your main module controller file-name.
ex: your module controller name as "IndexController" then test-module controller file name should be "IndexControllerTest".

IndexControllerTest.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
 
namespace ApplicationTest\Controller;
use ApplicationTest\Bootstrap;
use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;
use Application\Controller\IndexController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use Zend\Test\PHPUnit\Controller\AbstractControllerTestCase;
// use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class IndexControllerTest extends AbstractControllerTestCase
{
    protected $controller;
    protected $request;
    protected $response;
    protected $routeMatch;
    protected $event;
    protected $userMockObj;
    protected $serviceManager;
    
    public function setUp()
    {
        $this->serviceManager = Bootstrap::getServiceManager();
        $this->controller = new IndexController();
        $this->request    = new Request();
        $this->routeMatch = new RouteMatch(array('controller' => 'index'));
        $this->event      = new MvcEvent();
        $config = $this->serviceManager->get('Config');
        $routerConfig = isset($config['router']) ? $config['router'] : array();
        $router = HttpRouter::factory($routerConfig);
         
        $this->event->setRouter($router);
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
        $this->controller->setServiceLocator($this->serviceManager);
        $this->userMockObj = $this->getMockBuilder('Application\Model\TestModel')
                                    ->disableOriginalConstructor()
                                    ->getMock();
        $this->setApplicationConfig(
                include __DIR__.'/../../TestConfig.php'
        );
        parent::setUp();
    }
    
    public function testWorkAction() 
    {
        $this->serviceManager->setAllowOverride(true);
        $this->serviceManager->setService('Application\Model\TestModel', $this->userMockObj);
        
        $this->routeMatch->setParam('action', 'work');
        $response = $this->controller->getResponse();
        $result   = $this->controller->dispatch($this->request, $response);
        
        $this->assertEquals(200, $response->getStatusCode());
        
        // Check a ViewModel has been returned
        $this->assertInstanceOf('Zend\View\Model\ViewModel', $result);
        
        // Test against the test data
        $variables = $result->getVariables();
        $this->assertArrayHasKey('name', $variables);
        // Very lazy validation of data ;-)
        $this->assertEquals('OSSCube1', $variables["name"]);

        $this->dispatch('/index');
        $this->assertModuleName('Application');
        $this->assertControllerClass('IndexController');
        $this->assertMatchedRouteName('xyz');
        $this->assertControllerName('Application\Controller\Index');
    }

    public function testMemory() {
        $this->assertGreaterThanOrEqual(699328, memory_get_usage());
    }
}
?>


Now your directory structure would look like as:


Step 7: Run the phpunit inside of the "test" directory. then you will see some output if your test run successfully like as :

#phpunit
PHPUnit 4.1.3 by Sebastian Bergmann.
..
Time: 00:00
OK (2 tests)

Step 8: Some time you will get error, then there would be some code return that has some significant role like as:
. Printed when the test succeeds.
F Printed when an assertion fails while running the test method.
E Printed when an error occurs while running the test method.
S Printed when the test has been skipped.
I  Printed when the test is marked as being incomplete or not yet implemented.
Step 9: To get the html report for the code coverage analysis of your code, it's a 
feature of the phpunit to get the beautiful html formatted dashboard and reports.
To get this feature you have to install the PHP xDebug module.
# sudo pecl install xdebug 
Now, You can create the report by the below command:
# phpunit --coverage-html dir-name
Here, dir-name is the directory where you will put the report content. It will take bit of time to generate the html report. Once your report generated then just open the index.html file in your browser....










To see the code coverage for the tested code:



















In similar way you can get the dashboard on click of dashboard link that contain nice graph(s):
















I hope it will help you to run PHPUnit in Zend Framework-2. If anybody got issue during setup, Please put your comment, i highly appreciate that.. :)