Upload
hathanh13
View
243
Download
0
Embed Size (px)
Citation preview
8/2/2019 Cakephp Test
1/22
http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way
Testing CakePHP Controllers the hard way
Dec 18 2008
Practices and Habits, Auth, testing, Web Development, CakePHP, PHP
By now you already know or should know about CakeTestCase::testAction() and the
wondrous things it can do. However, testAction has a few shortcomings. It cant handle
redirects, it doesnt let you use the power of Mocks, and its impossible to make assertions onobject state changes. Sometimes you need to do things the hard way, stick your fingers in the mudand work it out. However, knowing how to test a controller the old fashioned way takes a goodknowledge of CakePHP.
Doing things the hard way
Controllers require a number of callbacks to be called before they are workable objects. So lets go,well start with the venerable PostsController, and make a nice test for it.
Show Plain Text
1.2.
8/2/2019 Cakephp Test
2/22
19. $this->stopped = $status;20. }21. }22.23. class PostsControllerTestCase extends CakeTestCase {
24. var $fixtures = array('app.post', 'app.comment', 'app.posts_tag', 'app.tag');25.26. function startTest() {27.28. }29.30. function endTest() {31.32. }33. }34. ?>
35.
So we start off with a basic test class, important things to notice are the fixtures array, and the testclass. Ive included all the fixtures that are related to the models my controller is going to use. Thisis important, as you will get tons of table errors until they are all setup.
You may have noticed that I created a subclass of the test subject, this lets me do a few things.First I can test functions that call redirect(), as they no longer redirect. I can also call methods thatuse $this->_stop() as they no longer halt script execution. Furthermore, I override
Controller::render() so I can test actions that use render() without having to deal with piles of
HTML. I personally dont do many tests that assert the html of my views because I find it takes too
much time and is tedious. Lastly, I set $autoRender to false just in case.
Show Plain Text
1. function startTest() {2. $this->Posts = new TestPostsController();3. $this->Posts->constructClasses();4. $this->Posts->Component->initialize($this->Posts);5. }6.7. //tests are going to go here.
8.9. function endTest() {10. unset($this->Posts);11. ClassRegistry::flush();12. }
http://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/unsethttp://www.php.net/flushhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/unsethttp://www.php.net/flush8/2/2019 Cakephp Test
3/22
We then build the instance and call some basic callbacks, much like Daniel blogged about . At thispoint we have a controller instance and all the components and models built. We are now ready tostart doing some testing.
Testing a controller method
Testing a controller method is just like testing any other method. Often there is a bit more setupinvolved as controllers are require more inputs by nature. However, it is all achievable in the testsuite. So we are going to do a test of ouradmin_edit method. This admin_edit is straight out of
bake, so you should know what it looks like. Furthermore, I can show how you can test methodsthat involve components like Auth.
Show Plain Text
1. function testAdminEdit() {2. $this->Posts->Session->write('Auth.User', array(
3. 'id' => 1,4. 'username' => 'markstory',5. ));6. $this->Posts->data = array(7. 'Post' => array(8. 'id' => 2,9. 'title' => 'Best article Evar!',10. 'body' => 'some text',11. ),12. 'Tag' => array(13. 'Tag' => array(1,2,3),
14. )15. );16. //more to come.17. }
At this point Ive created the inputs I need for my controller action. Ive got a session, and sometest data. Ive provided enough information in the session that AuthComponent will let me by and
edit my records. However, many would say that you should bypass Auth entirely in your unittesting and just focus on the subject method. But being thorough never hurt.
Show Plain Text
1. function testAdminEdit() {2. $this->Posts->Session->write('Auth.User', array(3. 'id' => 1,4. 'username' => 'markstory',5. ));6. $this->Posts->data = array(7. 'Post' => array(
http://cakebaker.42dh.com/2008/11/26/how-to-create-an-instance-of-a-controller/http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://cakebaker.42dh.com/2008/11/26/how-to-create-an-instance-of-a-controller/http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/array8/2/2019 Cakephp Test
4/22
8. 'id' => 2,9. 'title' => 'Best article Evar!',10. 'body' => 'some text',11. ),12. 'Tag' => array(
13. 'Tag' => array(1,2,3),14. )15. );16. $this->Posts->params = Router::parse('/admin/posts/edit/2');17. $this->Posts->beforeFilter();18. $this->Posts->Component->startup($this->Posts);19. $this->Posts->admin_edit();20. }
Ive now simulated most of a request in CakePHP. It is important to fire the callbacks in thecorrect order. Just remember that beforeFilter happens before Component::startup(), and
Component::beforeRender() happens after you call your controller action.
Making assertions
When I test controllers I usually make assertions on the viewVars that are set and any records thatare modified / deleted. I dont like making assertions on the contents of$this->Session-
>setFlash() as I find these messages change often which can lead to broken tests, which leads to
frowns. Continuing from before:
Show Plain Text
1. function testAdminEdit() {2. $this->Posts->Session->write('Auth.User', array(3. 'id' => 1,4. 'username' => 'markstory',5. ));6. $this->Posts->data = array(7. 'Post' => array(8. 'id' => 2,9. 'title' => 'Best article Evar!',10. 'body' => 'some text',11. ),
12. 'Tag' => array(13. 'Tag' => array(1,2,3),14. )15. );16. $this->Posts->params = Router::parse('/admin/posts/edit/2');17. $this->Posts->beforeFilter();18. $this->Posts->Component->startup($this->Posts);19. $this->Posts->admin_edit();
http://www.php.net/arrayhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/array8/2/2019 Cakephp Test
5/22
20.21. //assert the record was changed22. $result = $this->Posts->Post->read(null, 2);23. $this->assertEqual($result['Post']['title'], 'Best article Evar!');24. $this->assertEqual($result['Post']['body'], 'some text');
25. $this->assertEqual(Set::extract('/Tag/id', $result), array(1,2,3));26.27. //assert that some sort of session flash was set.28. $this->assertTrue($this->Posts->Session->check('Message.flash.message'));29. $this->assertEqual($this->Posts->redirectUrl, array('action' => 'index'));30. }
So there you go a nice simple test for a controller, with redirects and session flashes. Since we aretesting with the real session we should do the following to ensure there is no bleed throughbetween tests.
Show Plain Text
1. function endTest() {2. $this->Posts->Session->destroy();3. unset($this->Posts);4. ClassRegistry::flush();5. }
By destroying the session we ensure that we have a clean slate on each test method. So thats itreally testing controllers really isnt as hard as it may seem. There are some additional tricks thatcan be done with Mocks but that is another article all together.
http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-
1-2-test-suite
Testing Models with CakePHP 1.2 test suite
CakePHP test suite is a powerful environment that lets you test small to large applications testingfor isolated portions of your code. It is one of the coolest additions to the 1.2 release and in thisarticle we'll see how to use it to test our application models.
Installation
First of all, you'll need to enable the test suite for your CakePHP 1.2 installation. After CakePHP issuccesfully installed and configured, get the latest release of SimpleTest fromits website, anduncompress it in either yourcake/vendors or yourapp/vendors directory. You should have now avendors/simpletest directory with all SimpleTest files and folders inside.
Make sure that you at least have a DEBUG level of1 in yourapp/config/core.php file. Test your
http://www.php.net/extracthttp://www.php.net/arrayhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/unsethttp://www.php.net/flushhttp://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://simpletest.sourceforge.net/http://simpletest.sourceforge.net/http://www.php.net/extracthttp://www.php.net/arrayhttp://www.php.net/arrayhttp://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way#nullhttp://www.php.net/unsethttp://www.php.net/flushhttp://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://simpletest.sourceforge.net/8/2/2019 Cakephp Test
6/22
installation by running any of CakePHP core tests, pointing your browser tohttp://www.example.com/test.php.
About Fixtures
When testing models it is important to understand the concept of fixtures in CakePHP test suite.Fixtures are a way for you to define sample data that will be loaded in your models and will allowyou to perform your testing. CakePHP uses its own settings for fixtures to not disrupt your realapplication data.
CakePHP will look at your app/config/database.php configuration file and test if the connectionnamed $test is accessible. If so, it will use it to hold fixture data. Otherwise it will use the $defaultdatabase configuration. On either case, it will add "test_suite" to your own table prefix (if any) toprevent collision with your existing tables.
CakePHP will perform different operations during different stages of your fixtured based test
cases:
1. Before running the first test method in your test case, it will create the tables for each ofyour fixtures.
2. Before running any test method, it will optionally populate records for each of yourfixtures.
3. After running each test method, it will empty each of your fixture tables.4. After running your last test method, it will remove all your fixture tables.
Creating Fixtures
When creating a fixture you will mainly define two things: how the table is created(which fields are part of the table), and which records will be initially populated to the
test table. Let's then create our first fixture, that will be used to test our own Article
model. Create a file named article_test_fixture.php in your app/tests/fixtures
directory, with the following content:
PHP Snippet:
8/2/2019 Cakephp Test
7/22
'updated' => 'datetime'
);
var $records = array(
array ('id' => 1, 'title' => 'First Article', 'body' => 'First Article
Body', 'published' => '1', 'created' => '2007-03-18 10:39:23', 'updated' => '
2007-03-18 10:41:31'),
array ('id' => 2, 'title' => 'Second Article', 'body' => 'Second Arti
cle Body', 'published' => '1', 'created' => '2007-03-18 10:41:23', 'updated'
=> '2007-03-18 10:43:31'),
array ('id' => 3, 'title' => 'Third Article', 'body' => 'Third Article
Body', 'published' => '1', 'created' => '2007-03-18 10:43:23', 'updated' => '
2007-03-18 10:45:31')
);
}
?>
We use $fields to specify which fields will be part of this table, on how they are
defined. The format used to define these fields is the same used in the function
generateColumnSchema() defined on Cake's database engine classes (forexample, on file dbo_mysql.php.) Let's see the available attributes a field can take
and their meaning:
1. type: CakePHP internal data type. Currently supported: string (maps toVARCHAR), text (maps to TEXT), integer (maps to INT), float (maps to FLOAT),datetime (maps to DATETIME), timestamp (maps to TIMESTAMP), time (maps to
TIME), date (maps to DATE), and binary (maps to BLOB)2. key: set to primary to make the field AUTO_INCREMENT, and a PRIMARY KEY
for the table.3. length: set to the specific length the field should take.4. null: set to either true (to allow NULLs) or false (to disallow NULLs)5. default: default value the field takes.
We lastly can set a set of records that will be populated after the test table is created.
The format is fairly straight forward and needs no further explanation.
Importing table information and records
Your application may have already working models with real data associated to them,
and you might decide to test your model with that data. It would be then a duplicateeffort to have to define the table definition and/or records on your fixtures.
Fortunately, there's a way for you to define that table definition and/or records for a
particular fixture come from an existing model or an existing table.
Let's start with an example. Assuming you have a model named Article available in
your application (that maps to a table named articles), change the example fixture
given in the previous section (app/tests/fixtures/article_test_fixture.php) to:
8/2/2019 Cakephp Test
8/22
PHP Snippet:
This statement tells the test suite to import your table definition from the table linked
to the model called Article. You can use any model available in your application. The
statement above does not import records, you can do so by changing it to:
PHP Snippet:
If on the other hand you have a table created but no model available for it, you can
specify that your import will take place by reading that table information instead. For
example:
PHP Snippet:
Will import table definition from a table called 'articles' using your CakePHP database
connection named 'default'. If you want to change the connection to use just do:
PHP Snippet:
Since it uses your CakePHP database connection, if there's any table prefix declared it
will be automatically used when fetching table information. The two snippets above
do not import records from the table. To force the fixture to also import its records,
change it to:
8/2/2019 Cakephp Test
9/22
PHP Snippet:
You can naturally import your table definition from an existing model/table, but have
your records defined directly on the fixture as it was shown on previous section. For
example:
PHP Snippet:
Creating your test case
Let's say we already have our Article model defined on app/models/article.php, which
looks like this:
Model Class:
8/2/2019 Cakephp Test
10/22
return $this->findAll($conditions, $fields);
}
}
?>
We now want to set up a test that will use this model definition, but through fixtures,
to test some functionality in the model. CakePHP test suite loads a very minimum set
of files (to keep tests isolated), so we have to start by loading our parent model (in
this case the Article model which we already defined), and then inform the test suite
that we want to test this model by specifying which DB configuration it should use.
CakePHP test suite enables a DB configuration named test_suite that is used for all
models that rely on fixtures. Setting $useDbConfig to this configuration will let
CakePHP know that this model uses the test suite database connection.
Since we also want to reuse all our existing model code we will create a test model
that will extend from Article, set $useDbConfig and $name appropiately. Let's now
create a file named article.test.php in your app/tests/cases/models directory,with the following contents:
PHP Snippet:
As you can see we're not really adding any test methods yet, we have just defined
our ArticleTest model (that inherits from Article), and created the ArticleTestCase. In
variable $fixtures we define the set of fixtures that we'll use.
Creating our first test method
Let's now add a method to test the function published() in the Article model. Edit thefile app/tests/cases/models/article.test.php so it now looks like this:
PHP Snippet:
8/2/2019 Cakephp Test
11/22
class ArticleTest extends Article {
var $name = 'ArticleTest';
var $useDbConfig = 'test_suite';
}
class ArticleTestCase extends CakeTestCase {
var $fixtures = array( 'article_test' );
function testPublished() {
$this->ArticleTest =& new ArticleTest();
$result = $this->ArticleTest->published(array('id', 'title'));
$expected = array(
array('ArticleTest' => array( 'id' => 1, 'title' => 'First Articl
e' )),
array('ArticleTest' => array( 'id' => 2, 'title' => 'Second Artic
le' )),
array('ArticleTest' => array( 'id' => 3, 'title' => 'Third Articl
e' ))
);
$this->assertEqual($result, $expected);
}
}
?>
You can see we have added a method called testPublished(). We start by creating
an instance of our fixture based ArticleTest model, and then run our published()
method. In $expected we set what we expect should be the proper result (that we
know since we have defined which records are initally populated to the article_tests
table.) We test that the result equals our expectation by using the assertEqual
method.
Running your test
Make sure that you at least have a DEBUG level of1 in your app/config/core.phpfile, and then point your browser to http://www.example.com/test.php. Click on AppTest Cases and find the link to your models/article.test.php. Click on that link.
If everything works as expected, you will see a nice green screen saying that yourtest succeded.
Comments
http://www.example.com/test.phphttp://bakery.cakephp.org/users/view/crouchjayhttp://www.example.com/test.php8/2/2019 Cakephp Test
12/22
crouchjay
Posted 01/19/09 08:07:24 PM
I was running into a lot of problems with using associations and this bit helped me out.
No need for ModelNameTest extends ModelName {}
Use
App::import('Model', 'ModelName');
class ModelNameTestCase extends CakeTestCase {
var $fixtures = array('model1_test', 'model2_test');
function testFunction() {$model = ClassRegistry::init('ModelName');}}
Hope this helps..
Report this
davidsblom
Posted 01/12/09 12:36:30 PM
Hi!I'm not sure if this is the right place to ask this kind of questions, but I'll do it anyways. :)I would like to load different fixtures for one model on demand. I'm not sure if this ispossible with CakePHP. I thought this functionality is implemented on RoR, but I'm not
completely sure.If it's not possible to do right now, it would nice to add this feature in future versions ofCakePHP. :)Thanks.David
Edit: I've found the solution to my own problem.When autoFixtures is set to false, the fixtures are not loaded automatically. They can be
http://bakery.cakephp.org/users/view/crouchjayhttp://bakery.cakephp.org/report/Comment/4caea155-62c4-4a12-bfc0-4cb382f0cb67http://bakery.cakephp.org/users/view/davidsblomhttp://bakery.cakephp.org/users/view/davidsblomhttp://bakery.cakephp.org/users/view/crouchjayhttp://bakery.cakephp.org/report/Comment/4caea155-62c4-4a12-bfc0-4cb382f0cb67http://bakery.cakephp.org/users/view/davidsblom8/2/2019 Cakephp Test
13/22
loaded with the handy function loadFixtures().More information can be found in the api:
http://api.cakephp.org/tests/class_cake_test_case.html#fb2bddc87d12ed0c4ee0d6bc5b83e98e
Report this
dericknwq
Posted 05/25/08 02:15:50 AM
I find the import pretty useful but is there a way to limit the no. of records imported? In thiscase, we might have too many records yet it'd be useful to just have some of them beingused during tests.
Report this
bhushanahirrao
Posted 04/17/08 06:44:49 AM
I have followed the steps you mentioned above. But still I am gettng 'Fatal error: Class'User' not found in /tests/cases/models/user.test.php' I am putting my user.test.php's codehere. Please let me know what i am missing.
App::import('User','User');
class UserTest extends User{var $name = 'UserTest ';var $useDbConfig = 'test_suite';
}
class UserTest Case extends CakeTestCase {
http://api.cakephp.org/tests/class_cake_test_case.html#fb2bddc87d12ed0c4ee0d6bc5b83e98ehttp://api.cakephp.org/tests/class_cake_test_case.html#fb2bddc87d12ed0c4ee0d6bc5b83e98ehttp://bakery.cakephp.org/report/Comment/4caea154-f224-42f7-99f8-4e2282f0cb67http://bakery.cakephp.org/users/view/dericknwqhttp://bakery.cakephp.org/report/Comment/4caea132-c4a4-4844-ad05-4e5682f0cb67http://bakery.cakephp.org/users/view/bhushanahirraohttp://bakery.cakephp.org/users/view/bhushanahirraohttp://bakery.cakephp.org/users/view/dericknwqhttp://api.cakephp.org/tests/class_cake_test_case.html#fb2bddc87d12ed0c4ee0d6bc5b83e98ehttp://api.cakephp.org/tests/class_cake_test_case.html#fb2bddc87d12ed0c4ee0d6bc5b83e98ehttp://bakery.cakephp.org/report/Comment/4caea154-f224-42f7-99f8-4e2282f0cb67http://bakery.cakephp.org/users/view/dericknwqhttp://bakery.cakephp.org/report/Comment/4caea132-c4a4-4844-ad05-4e5682f0cb67http://bakery.cakephp.org/users/view/bhushanahirrao8/2/2019 Cakephp Test
14/22
var $fixtures = array( 'user_test' );function testInactive() {$this->UserTest =& new UserTest ();
$result = $this->UserTest ->inactive(array('id', 'name'));
$expected = array(array('UserTest ' => array( 'id' => 1, 'name' => 'User Communities' ))
);
$this->assertEqual($result, $expected);}}?>
PLease reply. Waiting for your reply.
Report this
lmolina
Posted 03/14/08 12:06:01 PM
Hello Mariano, thanks for the tutorial.
Here's my issue, I created a simple silly test to practice, I think I follow all the instructionsyou give, but the suite does not seem to be creating the test tables.
I get this error:
Error: Database table test_suite_albums for model Album was not found.
And I'm using this fixture (I tried specifying the table definition as well with no luck):
8/2/2019 Cakephp Test
15/22
array ('id' => 2, 'artist_id' => '2', 'name' => 'Album 2 Name','year' => '1999'),
array ('id' => 3, 'artist_id' => '3', 'name' => 'Album 3 Name','year' => '2001'),
array ('id' => 4, 'artist_id' => '4', 'name' => 'Album 4 Name','year' => '2005')
);}?>
Please help!
Report this
Expand this thread
jach786
Posted 02/07/08 05:20:27 AM
Hello All,
I have try to test my modules but it gives error that
Fatal error: Class 'Object' not found inC:\\xampp\\htdocs\\sch\\cake\\libs\\model\\datasources\\datasource.php on line 37
my testing location is C:\\xampp\\htdocs\\sch\\app\\tests\\app\\cases\\models
Could any body help me for this.
Regards,
Report this
Expand this thread
http://bakery.cakephp.org/report/Comment/4caea12a-27c0-4420-8bd5-4d7582f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/jach786http://bakery.cakephp.org/users/view/jach786http://bakery.cakephp.org/report/Comment/4caea126-f4e4-40d8-82fb-4d1582f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/PhilipRhttp://bakery.cakephp.org/users/view/jach786http://bakery.cakephp.org/report/Comment/4caea12a-27c0-4420-8bd5-4d7582f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/jach786http://bakery.cakephp.org/report/Comment/4caea126-f4e4-40d8-82fb-4d1582f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suite8/2/2019 Cakephp Test
16/22
PhilipR
Posted 12/19/07 04:48:04 PM
I had accidentally named tournament_game_test_fixture.php in the plural,
tournament_**games**_test_fixture.php . I'm still not getting fixtures working 100%, butat least I'm more on track now.
Report this
winescout
Posted 04/29/07 01:37:13 AM
Here is my fix for my issue with testing the creation of new objects from within a model. (Ialso posted it on Trac).
This may not work for everyone, as it assumes that you don't have any tables with the samename in separate db's. But, I suspect that is most people :). basically all I did was removethe 'test_suite_' prefix for table names, which seems redundant to me, and removed theability to test in the same db as 'default', which seems like a bad idea anyways.
If you want to do this, have all your test classes inherit from this class, and apply the diffbelow to your /app/cake directory. Then name your fixtures the same thing as your Modelnames.
class TestCase extends CakeTestCase{
function before($method){if (!defined('ENVIRONMENT')){
define("ENVIRONMENT", "testing");}parent::before($method);}
}
?>
http://bakery.cakephp.org/users/view/PhilipRhttp://bakery.cakephp.org/report/Comment/4caea120-fa38-45f0-81e6-4a1e82f0cb67http://bakery.cakephp.org/users/view/winescouthttp://bakery.cakephp.org/users/view/winescouthttp://bakery.cakephp.org/users/view/PhilipRhttp://bakery.cakephp.org/report/Comment/4caea120-fa38-45f0-81e6-4a1e82f0cb67http://bakery.cakephp.org/users/view/winescout8/2/2019 Cakephp Test
17/22
Here is the diff ----------------
ndex: tests/lib/cake_test_case.php===================================================================--- tests/lib/cake_test_case.php (revision 4896)+++ tests/lib/cake_test_case.php (working copy)@@ -57,17 +57,8 @@@$db =& ConnectionManager::getDataSource('test');set_error_handler('simpleTestErrorHandler');
- // Try for default DB
- if (!$db->isConnected()) {- $db =& ConnectionManager::getDataSource('default');- }-- // Add test prefix- $config = $db->config;- $config['prefix'] .= 'test_suite_';-// Set up db connection- ConnectionManager::create('test_suite', $config);+ ConnectionManager::create('test_suite', $db->config);
// Get db connection$this->db =& ConnectionManager::getDataSource('test_suite');Index: libs/model/connection_manager.php===================================================================--- libs/model/connection_manager.php (revision 4890)+++ libs/model/connection_manager.php (working copy)@@ -93,8 +93,11 @@* @return object*/function &getDataSource($name) {+ if(defined('ENVIRONMENT') && ENVIRONMENT == 'testing'){+ $name = 'test';+ }+$_this =& ConnectionManager::getInstance();-if (in_array($name, array_keys($_this->_dataSources))) {
8/2/2019 Cakephp Test
18/22
return $_this->_dataSources[$name];}
Report this
Expand this thread
mariano
Posted 04/24/07 02:25:59 PM
@mattclark: Typo corrected, thanks for the heads up. Always update to the latest SVNhead when using CakePHP 1.2 since it is still on alpha stage. Try that and let me know.
Report this
Expand this thread
winescout
Posted 04/24/07 02:35:58 AM
Hi, I'm really excited to see Cake intigrate unit tests. Great work. Thanks for the excellentarticle explaining everything too.
Small bug on the page, the tests dir is plural. You refer to it in paths as singular in fewplaces. For example - (app/test/fixtures/article_test_fixture.php)
Also, I'm having a bugger of a time getting fixtures to load up. I've followed the examplesalmost exactly, but still get this in the test output - "No Database table for model UserTest
http://bakery.cakephp.org/report/Comment/4caea10e-3a80-41fe-9481-44bf82f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10e-245c-4e1d-b808-4b1482f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/winescouthttp://bakery.cakephp.org/users/view/winescouthttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10e-3a80-41fe-9481-44bf82f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10e-245c-4e1d-b808-4b1482f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/winescout8/2/2019 Cakephp Test
19/22
(expected test_suite_user_tests), create it first."
Any Chance things are still a bit buggy in 1.2.0.4798alpha?
Report this
mariano
Posted 04/23/07 06:36:49 PM
@Sonic:
1. Please read the article entirely. Look for section "Importing table information andrecords" and you'll see that you can import your current table schema from existingmodels/tables.
2. Again, read the article, particularly section "About Fixtures". You can set up your $testconnection with persistent set to false and that's exactly what you will achieve.
3. It is up to you what you expect and how you do the matching. You can expect exactrecords, or dynamically generated records. For example your test could be against afindCount(), and you could $this->assertTrue($result > 5);
4. It was exactly the opposite way. Larry asked a long time ago to dhofstet to contribute toCake's built in Test Suite, but instead he rolled out his own. Nothing good or bad, just theway it happened.
Report this
Expand this thread
sonic
Posted 04/23/07 05:06:53 PM
http://bakery.cakephp.org/report/Comment/4caea10e-62b0-4802-a126-4a5782f0cb67http://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10e-b974-4799-b823-492c82f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/sonichttp://bakery.cakephp.org/users/view/sonichttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10e-62b0-4802-a126-4a5782f0cb67http://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10e-b974-4799-b823-492c82f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/sonic8/2/2019 Cakephp Test
20/22
Hi Mariano,
First of all can I say that I am excited that testing is now being integrated with CakePHP.However, there are a few things I'd like to ask about your testing framework.
1.First of all, why the fields array? This means that I have to duplicate my database schemain my SQL file and my tests. Doesn't this go against the DRY principal?I do like the fact that the tables are recreated each time but wouldn't it be better to createthem from the SQL schema file for the application in question rather than repeat it in thefixture files?If I make a change to my database e.g. PhpMyAdmin. I can go and make this change to mytest fixtures (or let the fixture import it from the model) but forget to export the change tothe schema file under version control in my repository. Then, code that I commit, passingall tests and therefore assumed to be working, may in fact crash when someone checks itout of the repository because the schema file may have inconsistencies with the schema
used in the code.This is something I find I do all the time, maybe it's just me.
2.While asking questions about testing with a real database, Marcus Baker on (the creator ofSimpleTest) replied suggesting the use of a separate database connection for the schemacreation and the tests themselves. Although I can't quite remember why. Are you doingthis?
3.As you've set written the array of expected values in the test itself, it isn't clear whether thefixture data in the tests to dynamically test the results, as in $this->article_test->records[0][id] Is this possible?
4.It looks like this test suite has a lot in common with Dhofstets testing suite. Why did youguys decide to roll your own rather than work with this existing one.
I've been hoping for some good testing support for cake for a good while now. As such I'mvery excited about what's happening at the moment. Thanks for this. I hope my questionsseem valid.
Cheers,
Sonic
Report this
http://bakery.cakephp.org/report/Comment/4caea10e-7ef0-49f7-aeee-484d82f0cb67http://bakery.cakephp.org/report/Comment/4caea10e-7ef0-49f7-aeee-484d82f0cb678/2/2019 Cakephp Test
21/22
mariano
Posted 04/08/07 01:05:09 PM
@Mladen: I recommend you look at cake/tests/cases/libs/model/model.test.php, its fixturesare located at cake/tests/fixtures. You will see *A LOT* of models being tested, most ofthem with several relations.
Report this
mika
Posted 04/08/07 05:11:25 AM
This is great, you guys have put in so much work!
How would you test relations on the models? Just testing a single model is bit toosimplified in real world cases.
Report this
mariano
Posted 04/07/07 11:49:29 PM
@Zach: Not, leaving $fields out of the fixture definition will generate an error. However,post an enhancement ticket for 1.2 on the trac at https://trac.cakephp.org and I'll consideradding such functionality.
About writing more tutorials, I'll try to make time for it :)
http://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10d-b544-4508-95c5-464782f0cb67http://bakery.cakephp.org/users/view/mikahttp://bakery.cakephp.org/report/Comment/4caea10d-0530-4ff0-a5ed-442e82f0cb67http://bakery.cakephp.org/users/view/marianohttps://trac.cakephp.org/http://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/users/view/mikahttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10d-b544-4508-95c5-464782f0cb67http://bakery.cakephp.org/users/view/mikahttp://bakery.cakephp.org/report/Comment/4caea10d-0530-4ff0-a5ed-442e82f0cb67http://bakery.cakephp.org/users/view/marianohttps://trac.cakephp.org/8/2/2019 Cakephp Test
22/22
Report this
mariano
Posted 04/07/07 08:14:08 PM
@Zach: if you read the article when I talk about fixtures I mention the intention of notmanipulating nor disrupting your application data. Also, your fixtures could be running ona completely separate database than your application. The idea is that you can even testyour models with new fields that you have not yet added to your application, thus fixturesnot only specify which records are initially populated, but also how the table is built.
Report this
Expand this thread
zcox
Posted 04/07/07 07:57:04 PM
Is it really necessary to specify the database table $fields in the fixture? This seems likeduplicated effort and a real time sink for testing. Can Cake just use the existing table?
Report this
http://bakery.cakephp.org/report/Comment/4caea10d-3394-423d-ab99-40e782f0cb67http://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10d-2c4c-4def-ad95-420482f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/zcoxhttp://bakery.cakephp.org/users/view/zcoxhttp://bakery.cakephp.org/report/Comment/4caea10d-b4ac-450e-a493-483e82f0cb67http://bakery.cakephp.org/users/view/zcoxhttp://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10d-3394-423d-ab99-40e782f0cb67http://bakery.cakephp.org/users/view/marianohttp://bakery.cakephp.org/report/Comment/4caea10d-2c4c-4def-ad95-420482f0cb67http://bakery.cakephp.org/articles/mariano/2007/04/13/testing-models-with-cakephp-1-2-test-suitehttp://bakery.cakephp.org/users/view/zcoxhttp://bakery.cakephp.org/report/Comment/4caea10d-b4ac-450e-a493-483e82f0cb67