phpunit test class not found error while class is there? - zend-framework

This is my directory Structure
application
---modules
------admin
---------models
-----------User.php
This is my user Model class
class admin_Model_User
{
//User.php
}
This is my UserTest Class with simple AssertType
class admin_Model_UserTest
extends PHPUnit_Framework_TestCase
{
public function testUserModel()
{
$testUser = new admin_Model_User();
$this->assertType("admin_Model_User",$testUser);
}
}
When I run this. I am getting following Errors
[tests]# phpunit
PHPUnit 3.5.13 by Sebastian Bergmann.
0
Fatal error: Class 'admin_Model_User' not found in /web/zendbase/tests/application/modules/admin/models/UserTest.php on line 18
I know there my must be some path setting. I really could not able to figure out what is really wrong. Looking for help.....

You need to bootstrap Zend in your project's PHPUnit bootstrap.php file. Even though you are testing models and thus don't need the dispatcher, you must still have Zend_Application load application.ini and register its autoloader.
You can use Zend_Test_PHPUnit_ControllerTestCase to do the bootstrapping instead and make sure your model tests run after one of these, but that's a bit hacky.
Another option is to require_once the model classes manually for each test. The reason this doesn't work automatically via PHPUnit's autoloader is that it doesn't know how to transform the "namespace" admin_Model into the path admin/models.
Finally, you could write a simple autoloader to replace the one in PHPUnit. Before converting underscores to slashes, check if the class begins with the "namespace" above and replace it if so.

All I need to do is this
//file:ControllerTestCase.php
<?php
require_once GLOBAL_LIBRARY_PATH. '/Zend/Application.php';
require_once GLOBAL_LIBRARY_PATH. '/Zend/Test/PHPUnit/ControllerTestCase.php';
abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
protected $_application;
protected function setUp()
{
$this->bootstrap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap()
{
$this->_application = new Zend_Application(APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$this->_application->bootstrap();
/**
* Fix for ZF-8193
* http://framework.zend.com/issues/browse/ZF-8193
* Zend_Controller_Action->getInvokeArg('bootstrap') doesn't work
* under the unit testing environment.
*/
$front = Zend_Controller_Front::getInstance();
if($front->getParam('bootstrap') === null) {
$front->setParam('bootstrap', $this->_application->getBootstrap());
}
}
}
// and then require_once it in Bootstrap file.
thats all :) it is working.

Related

I have a trouble when i up code to host

This is my trouble:
Fatal error: Class 'Default_Model_Category' not found in
/home/u988704384/public_html/mutilmodules1/application/modules/default/controllers/IndexController.php
on line 89
But in localhost, it run normal.
Please help me solve it.
In file category.php:(/public_html/mutilmodules1/application/modules/default/models/)
<?php
class Default_Model_Category extends Zend_Db_Table
{
protected $_name = 'categories';
public function listinfo()
{
$data=$this->fetchall();
return $data;
}
}
In file IndexController.php: (/public_html/mutilmodules1/application/modules/default/controllers/)
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$category = new Default_Model_Category();
$this->view->entries = $category->listinfo();
}
}
The Zend Framework classes are either missing from your library folder, or not readable by the web server. First step is to see whether /home/u988704384/public_html/mutilmodules1/application/library/Zend/Application.php exists. If so, check the permissions on the library folder.
Could your current issue be as simple as a case issue? Your class is named Default_Model_Category but you seem to indicate that the file name is category.php. Try renaming the file to Category.php and see if that corrects the issue. I know I've run into this issue before when developing on my Mac, which doesn't care about case, but my LAMP server does.

How to add your own library to Zend Framework

So i have been designig an application to run on the Zend Framework 1.11 And as any programmer would do when he sees repeated functionalities i wanted to go build a base class with said functionalities.
Now my plan is to build a library 'My' so i made a folder in the library directory in the application. So it looks like this
Project
Application
docs
library
My
public
test
So i created a BaseController class in the My folder and then decided to have the IndexController in my application extend the BaseController.
The Basecontroller looks like this :
class My_BaseController extends Zend_Controller_Action
{
public function indexAction()
{
$this->view->test = 'Hallo Wereld!';
}
}
And the IndexController looks like this :
class WMSController extends My_BaseController
{
public function indexAction()
{
parent::indexAction();
}
}
As adviced by a number of resources i tried adding the namespace for the library in the application.ini using the line
autoloadernamespaces.my = “My_”
But when i try to run this application i recieve the following error
Fatal error: Class 'My_BaseController' not found in
C:\wamp\www\ZendTest\application\controllers\IndexController.php
Am i missing something here? Or am i just being a muppet and should try a different approach?
Thanks in advance!
Your original approach will work for you in application.ini, you just had a couple of problems with your set up.
Your application.ini should have this line:-
autoloadernamespaces[] = "My_"
Also, you have to be careful with your class names, taking your base controller as an example, it should be in library/My/Controller/Base.php and should look like this:-
class My_Controller_Base extends Zend_Controller_Action
{
public function indexAction()
{
$this->view->test = 'Hello World!';
}
}
You can then use it like this:-
class WMSController extends My_Controller_Base
{
public function indexAction()
{
parent::indexAction();
}
}
So, you had it almost right, but were missing just a couple of details. It is worth getting to know how autoloading works in Zend Framework and learning to use the class naming conventions
I don't know about .ini configuration, but I add customer libraries like this (index.php):
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->registerNamespace('My_');

Helper class cannot be found by autoloader in my Zend Framework application

I have the problem that in my ZF App the action helper cannot be loaded. The error message is:
Action Helper by name Sunshine not found
The layout of my ZF app uses modules where I have the following structure:
application
modules
weather
controllers
helpers
I have registered the helper in the modules Bootstrap which is located in
application -> modules -> weather -> Bootstrap.php
Here is the code
<?php
class Weather_Bootstrap extends Zend_Application_Module_Bootstrap
{
protected function _initActionHelperBrokers()
{
Zend_Controller_Action_HelperBroker::addPath('controllers/helpers', 'Weather_Controllers_Action_Helper_');
}
}
<?php
class Weather_Controller_Action_Helper_Sunshine extends Zend_Controller_Action_Helper_Abstract
{
public function getSunrise()
{
return "06:00";
}
}
<?php
class Weather_ForecastsController extends Zend_Controller_Action
{
protected function getForecasts($date)
{
$sunrise = $this->_helper->Sunshine->getSunrise();
// tbc
}
What is it, what I'm doing wrong here?
EDIT: As suggested I tried to add the helper in the bootstrap with the full path, but I got the same error.
the addPath method expects the entire path to the helper directory. Change it to something like:
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/modules/weather/controllers/helpers', 'Weather_Controllers_Action_Helper_');
Alternatively, you can also add the paths via your application.ini:
resources.frontController.actionhelperpaths.Weather_Controllers_Action_Helper = APPLICATION_PATH "/modules/weather/controllers/helpers"

Probable reasons why autoloading wont work in Zend Framework 1.10.2?

Iam writing an application using Zend Framework 1.10.2.
I created few model classes and a controller to process them.
When Iam executing my application and accessing the admin controller. Iam seeing this error.
Fatal error: Class 'Application_Model_DbTable_Users' not found in C:\xampp\htdocs\bidpopo\application\controllers\AdminController.php on line 16
The error clearly shows its an autoloading error.
Hence I wrote this code in the bootstrap file.
protected function initAutoload()
{
$modeLoader = new Zend_Application_Module_AutoLoader(array
('namespace'=>'','basePath'=>APPLICATION_PATH ));
//echo(APPLICATION_PATH);
return $modeLoader;
}
Still the error remains :( . Can anyone suggest me what Iam missing out here?
This is the location of the Model Users class.
C:\xampp\htdocs\bidpopo\application\models\DbTable\Users.php
This is its code.
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
//put your code here
protected $_name='users';
public function getUser($id)
{
$id = (int)$id;
$row = $this->fetchrow('id='.$id);
if(!$row)
{throw new Exception("Could not find row id - $id");}
return $row->toArray();
}
public function addUser($userDetailArray)
{
$this->insert($userDetailsArray);
}
public function updateUser($id,$userDetailArray)
{
$this->update($userDetailArray,'id='.(int)$id);
}
public function deleteUser($id)
{
$this->delete('id='. (int)$id);
}
}
This is the Admin Controller's code
class AdminController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$this->view->title= "All Users";
$this->view->headTitle($this->view->title);
$users = new Application_Model_DbTable_Users();
$this->view->users = $users->fetchAll();
}
public function addUserAction()
{
// action body
}
public function editUserAction()
{
// action body
}
public function deleteUserAction()
{
// action body
}
You application classes don't follow the proper naming convention for the namespace you've set. The Zend_Application_Module_AutoLoader is a little different than the normal autoloader in that it doesn't simply change the '_' in the class name with '/'. It looks at the second part of the class name and then checks a folder for the existence of the class based on that.
You need to change the line:
$modeLoader = new Zend_Application_Module_AutoLoader(array(
'namespace'=>'Application',
'basePath'=>APPLICATION_PATH
));
This means it will autoload all module classes prefixed with 'Application_'. When it the second part of the class is 'Model_' it will look in "{$basePath}/models" for the class. The '_' in the rest of the class name will be replaced with '/'. So the file path of the file will be "{$basePath}/models/DbTable/Users.php".
Read more here.

How to start testing Zend Framework Models?

How do I begin testing my models in a Zend Framework 1.8+ application?
Let's say I have my application set up to start testing. I have already tested a controller, so I know it works. I have all my controllers extending my ControllerTestCase.php file:
<?php
require_once 'Zend/Application.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
public $application;
public function setUp()
{
$this->application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$this->bootstrap = array($this, 'appBootstrap');
parent::setUp();
}
public function appBootstrap()
{
$this->application->bootstrap();
}
public function tearDown()
{
Zend_Controller_Front::getInstance()->resetInstance();
$this->resetRequest();
$this->resetResponse();
$this->request->setPost(array());
$this->request->setQuery(array());
parent::tearDown();
}
}
But now I want to start testing my models. It seems like my ModelTestCase.php would not extend Zend_Test_PHPUnit_ControllerTestCase but rather a Zend_Test_PHPUnit_ModelTestCase, but no such class exists that I know of. How can I start testing my Zend Framework models?
There is a base ControllerTestCase provided for you because there are complex steps needed to setup and tear down the environment for testing a controller. The input is a mock HTTP request, and the output is rendered HTML that you need to scrape to find expected content.
A Model is more like a plain old PHP object. There's less environment to set up. The interface is simply method calls to the object.
So I would start a TestCase class that extends PHPUnit's plain TestCase, and start by adding at least one test method (as an empty function) for each method in your Model class. You will eventually have many test methods for each method in your Model class, but creating the empty test methods is a good way to keep from forgetting some of your Model methods.
Note that a Model is not a Table -- a Model typically uses one or more Table objects. By following this pattern, you have the opportunity to create mock objects for Tables so you can run the test suite without requiring a live connection to a database.
Here's an example of setting up a mock Table object, which is hardcoded to return a synthetic data set instead of a data set from a database.
<?php
class MyModelTest extends PHPUnit_Framework_TestCase
{
protected $_model;
public function setUp()
{
$foo = $this->getMock('FooTable', array('find'));
$foo->expects($this->any())
->method('find')
->will($this->returnValue(array("id"=>"123")));
$this->_model = new MyModel();
$this->_model->setFooTable($foo);
}
public function testCountElements()
{
$this->_model->get(123);
$n = $this->_model->countElements();
$this->assertEquals(1, $n);
}
public function testAsArray()
{
$this->_model->get(123);
$a = $this->_model->asArray();
$this->assertType('array', $a);
}
public function testAddElement()
{
// ...etc.
}
public function testGetElement()
{
// ...etc.
}
}