The Newbie’s Guide to Test-Driven Development

The Newbie’s Guide to Test-Driven Development

Tutorial Details
  • Topic: PHP Testing
  • Version: PHP 5.2.13
  • Difficulty: Beginner
  • Estimated Completion Time: 1 hour

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Nettuts+. This tutorial was first published in August, 2010.

Testing your code is annoying, but the impact of not doing so can be orders of magnitude more annoying! In this article, we’ll use test-driven development to write and test our code more effectively.


What is Test-Driven Development?

Since the dawn of the computer era, programmers and bugs have battled for supremacy. It’s an inevitable occurrence. Even the greatest programmers fall prey to these anomalies. No code is safe. That’s why we do testing. Programmers, at least sane ones, test their code by running it on development machines to make sure it does what it’s supposed to.


Sane programmer who tests his programs.
Image courtesy of http://www.youthedesigner.com

Insane programmer who doesn’t test his programs.
Image courtesy of http://www.internetannoyanceday.com

Test-driven development is a programming technique that requires you to write actual code and automated test code simultaneously. This ensures that you test your code—and enables you to retest your code quickly and easily, since it’s automated.

How does it work?

Test-driven development, or TDD as we’ll call it from now on, revolves around a short iterative development cycle that goes something like this:

  1. Before writing any code, you must first write an automated test for your code. While writing the automated tests, you must take into account all possible inputs, errors, and outputs. This way, your mind is not clouded by any code that’s already been written.
  2. The first time you run your automated test, the test should fail—indicating that the code is not yet ready.
  3. Afterward, you can begin programming. Since there’s already an automated test, as long as the code fails it, it means that it’s still not ready. The code can be fixed until it passes all assertions.
  4. Once the code passes the test, you can then begin cleaning it up, via refactoring. As long as the code still passes the test, it means that it still works. You no longer have to worry about changes that introduce new bugs.
  5. Start the whole thing over again with some other method or program.

Great, but how is this better than regular testing?

Have you ever purposefully skipped testing a program because:

  • You felt it was a waste of time to test, since it was only a slight code change?
  • You felt lazy testing everything again?
  • You didn’t have enough time to test because the project manager wanted it moved up to production ASAP?
  • You told yourself you’d do it “tomorrow”?
  • You had to choose between manual testing, or watching the latest episode of your favorite TV show (Big Bang Theory)?

Most of the time, nothing happens, and you successfully move your code to production without any problems. But sometimes, after you’ve moved to production, everything goes wrong. You’re stuck fixing a hundred holes in a sinking ship, with more appearing every minute. You do not want to find yourself in this situation.


Screw it, just move it to production!
Image courtesy of http://phenomenaonbreak.wordpress.com

TDD was meant to eliminate our excuses. When a program has been developed using TDD, it allows us to make changes and test quickly and efficiently. All we need to do is run the automated tests, and voila! If it passes all automated tests, then we’re good to go—if not, then it just means we broke something with the changes. By knowing which exact parts of the test failed, it also allows us to easily pinpoint at which part of the changes it broke, so it makes fixing the bugs easier.


I’m Sold. How Do We Do This?

There’s a multitude of PHP automated testing frameworks out there we can use. One of the most widely-used testing frameworks is PHPUnit.

PHPUnit is a great testing framework, which can easily be integrated into your own projects, or other projects built on top of popular PHP frameworks.

For our purposes though, we won’t need the multitude of functions that PHPUnit offers. Instead, we’ll opt to create our tests using a much easier testing framework, called SimpleTest.

In the next steps, let’s assume that we’re developing a guestbook application where any user can add and view guestbook entries. Let’s assume that the markup has been completed, and that we’re simply making a class which contains the application logic of the guestbook, which is where the application inserts and reads to the database. The reading portion of this class is what we’re going to develop and test.


Step 1. Set up SimpleTest

This is arguably the easiest step of all. Even this guy could do it:


I can do this…I can use, my, um…brain!
Image courtesy of http://longstreet.typepad.com/

Download SimpleTest here, and extract to a folder of your choice — preferably the folder where you’re going to develop your code, or your PHP include_path for easy access.

For this tutorial, I’ve set up the folder like so:

Index.php will run guestbook.php, and invoke the view method and display the entries. Inside the classes folder is where we’ll put the guestbook.php class, and the test folder is where we place the simpletest library.


Step 2. Plan Your Attack

The second step, which is actually the most important one, is to start creating your tests. For this, you really need to plan and think about what your function will do, what possible inputs it will get, and the corresponding outputs it will send. This step resembles playing a game of chess—you need to know everything about your opponent (the program), including all his weaknesses (possible errors) and strengths (what happens if it successfully runs).

So for our guestbook application, let’s lay down the schematics:

View

  • This function will not have any inputs since it will just retrieve all of the entries from the database and send back the data to be printed out.
  • It will return an array of guestbook records, stating the name of the poster and his message. If there are no records, then it should still return an empty array.
  • If there are records, the array will have 1 or more values in it.
  • At the same time, the array will have a specific structure, something like:
Array (
    [0] => Array (
        ['name'] = "Bob"
        ['message'] = "Hi, I'm Bob."
    )
    [1] => Array (
        ['name'] = "Tom"
        ['message'] = "Hi, I'm Tom."
    )
)

Step 3. Write a Test!

Now, we can write our first test. Let’s start by creating a file called guestbook_test.php inside the test folder.

<?php
require_once(dirname(__FILE__) . '/simpletest/autorun.php');
require_once('../classes/guestbook.php');

class TestGuestbook extends UnitTestCase {

}

Then, let’s convert what we’ve determined from step two,.

<?php
require_once(dirname(__FILE__) . '/simpletest/autorun.php');
require_once('../classes/guestbook.php');

class TestGuestbook extends UnitTestCase {
    function testViewGuestbookWithEntries()
	{
		$guestbook = new Guestbook();
		// Add new records first
		$guestbook->add("Bob", "Hi, I'm Bob.");
		$guestbook->add("Tom", "Hi, I'm Tom.");
		$entries = $guestbook->viewAll();

		$count_is_greater_than_zero = (count($entries) > 0);
		$this->assertTrue($count_is_greater_than_zero);
		$this->assertIsA($entries, 'array');
		foreach($entries as $entry) {
			$this->assertIsA($entry, 'array');
			$this->assertTrue(isset($entry['name']));
			$this->assertTrue(isset($entry['message']));
		}
	}

	function testViewGuestbookWithNoEntries()
	{
		$guestbook = new Guestbook();
		$guestbook->deleteAll(); // Delete all the entries first so we know it's an empty table
		$entries = $guestbook->viewAll();
		$this->assertEqual($entries, array());
	}
}

Assertions make sure that a certain thing is what it’s supposed to be—basically, it ensures that what’s returned is what you’re expecting it to return. For example, if a function is supposed to return true if it’s successful, then in our test, we should assert that the return value is equal to true.

As you can see here, we test the viewing of the guestbook with entries and without. We check if these two scenarios pass our criteria from step two. You probably also noticed that each of our test functions start with the word ‘test.’ We did this because, when SimpleTest runs this class, it will look for all the functions that start with the word ‘test’ and run it.

In our test class, we’ve also used some assertion methods, such as assertTrue, assertIsA, and assertEquals. The assertTrue function checks whether or not a value is true. AssertIsA checks if a variable is of a certain type or class. And lastly, assertEquals checks if a variable is totally equal to a certain value.

There are other assertion methods provided by SimpleTest, which are:

assertTrue($x) Fail if $x is false
assertFalse($x) Fail if $x is true
assertNull($x) Fail if $x is set
assertNotNull($x) Fail if $x not set
assertIsA($x, $t) Fail if $x is not the class or type $t
assertNotA($x, $t) Fail if $x is of the class or type $t
assertEqual($x, $y) Fail if $x == $y is false
assertNotEqual($x, $y) Fail if $x == $y is true
assertWithinMargin($x, $y, $m) Fail if abs($x – $y) < $m is false
assertOutsideMargin($x, $y, $m) Fail if abs($x – $y) < $m is true
assertIdentical($x, $y) Fail if $x == $y is false or a type mismatch
assertNotIdentical($x, $y) Fail if $x == $y is true and types match
assertReference($x, $y) Fail unless $x and $y are the same variable
assertClone($x, $y) Fail unless $x and $y are identical copies
assertPattern($p, $x) Fail unless the regex $p matches $x
assertNoPattern($p, $x) Fail if the regex $p matches $x
expectError($x) Swallows any upcoming matching error
assert($e) Fail on failed expectation object $e

Assertion method list courtesy of http://www.simpletest.org/en/unit_test_documentation.html


Step 4. Fail to Win

Once you’re finished writing the code, you should run the test. The first time you run the test, it SHOULD FAIL. If it doesn’t, then it means that your test doesn’t really test anything.

To run your test, simply run guestbook_test.php in your browser. You should see this first:

This happened because we haven’t created our guestbook class yet. To do so, create guestbook.php inside your classes folder. The class should contain the methods we’re planning to use, but shouldn’t contain anything yet at first. Remember, we’re writing the tests first before writing any code.

<?php
class Guestbook
{

	public function viewAll() {

	}

	public function add( $name, $message ) {

	}

	public function deleteAll() {

	}
}

When you run the test again, it should look something like this:

As we can see here, our test is now winning by failing. This means that our test is now ready to get “answered.”


Step 5. Answer Your Test by Writing Code


At some point, we’ve all felt like this when we’re programming.
Image courtesy of http://fermentation.typepad.com/fermentation

Now that we have a working automated test, we can start writing code. Open up your guestbook.php class and start creating the answer to your test.

<?php
class Guestbook
{
	// To save time, instead of creating and connecting to a database, we're going to
	// simulate a "database" by creating a static entries array here.
	// It will be like we have two entries in the table.

	private static $_entries = array(
		array (
			'name' => 'Kirk',
			'message' => 'Hi, I\'m Kirk.'
		),
		array (
			'name' => 'Ted',
			'message' => 'Hi, I\'m Ted.'
		)
	);

	public function viewAll() {
		// Here, we should retrieve all the records from the database.
		// This is simulated by returning the $_entries array
		return self::$_entries;
	}

	public function add( $name, $message ) {
		// Here, we simulate insertion into the database by adding a new record into the $_entries array
		// This is the correct way to do it: self::$_entries[] = array('name' => $name, 'message' => $message );
		self::$_entries[] = array('notname' => $name, 'notmessage' => $message ); //oops, there's a bug here somewhere
		return true;
	}

	public function deleteAll() {
		// We just set the $_entries array to simulate
		self::$_entries = array();
		return true;
	}
}

This guestbook.php class has some bugs in it on purpose, so we can see what it looks like if our test fails.

Once we run our test, we should see something like this:

The test output shows us in which test and in which assertion our code failed. From this, we can easily pinpoint that line 16 and 17 was the assertion that threw the error.

<?php
require_once(dirname(__FILE__) . '/simpletest/autorun.php');
require_once('../classes/guestbook.php');

class TestGuestbook extends UnitTestCase {
...
...
...
	$this->assertTrue(isset($entry['name']));
	$this->assertTrue(isset($entry['message']));
...
...
...
}

This clearly tells us that the returned entry array did not have the correct array key. Based on this, we’ll easily know which part of our code went wrong.

<?php
class Guestbook
{
...
...
...
	public function add( $name, $message ) {
		// Here, we simulate insertion into the database by adding a new record into the $_entries array
		self::$_entries[] = array('name' => $name, 'message' => $message ); //fixed!
		return true;
	}
...
...
...
}

Now, when we run our test again, it should show us:


Step 6. Refactor and Refine Your Code

Since the code we’re testing here is pretty simple, our testing and bug fixing didn’t last very long. But if this was a more complex application, you’d have to make multiple changes to your code, make it cleaner so it’s easier to maintain, and a lot of other things. The problem with this, though, is that change usually introduces additional bugs. This is where our automated test comes in—once we make changes, we can simply run the test again. If it still passes, then it means we didn’t break anything. If it fails, we know that we made a mistake. It also informs us where the problem is, and, hopefully, how we’ll be able to fix it.


Step 7. Rinse and Repeat

Eventually, when your program requires new functionality, you’ll need to write new tests. That’s easy! Rinse and repeat the procedures from step two (since your SimpleTest files should already be set up), and start the cycle all over again.


Conclusion

There are a lot more in-depth test-driven development articles out there, and even more functionality to SimpleTest than what was displayed in this article—things like mock objects, stubs, which make it easier to create tests. If you’d like to read more, Wikipedia’s test-driven development page should set you on the right path. If you’re keen on using SimpleTest as your testing framework, browse the online documentation and be sure to review its other features.

Testing is an integral part of the development cycle, however, it’s too often the first thing to be cut when deadlines are imminent. Hopefully, after reading this article, you’ll appreciate how helpful it is to invest in test-driven development.

What are your thoughts on Test-Driven Development? Is it something you’re interested in implementing, or do you think it’s a waste of time? Let me know in the comments!

Add Comment

Discussion 63 Comments

  1. Oluf Nielsen says:

    Nice. I always wanted to learn this! It is GREAT!

  2. Eric Barnes says:

    Nice write up!

    For those using CodeIgniter and want to use SimpleTest I created an integration for it here:
    http://github.com/ericbarnes/codeigniter-simpletest

  3. This is a pretty good intro to testing. Hadn’t used SimpleTest myself, but it does seem like a good alternative to PHPUnit.

    I’ve written a bunch of articles which go more in-depth to unit testing practices in PHP, including how to test code which uses a database and how to write code that is easy to test.

    You can check them out here: http://codeutopia.net/blog/2009/08/17/unit-testing-essentials/

  4. Umair says:

    I was looking for unit testing tutorial and you got it for us, Thanks.

  5. w1sh says:

    Man those were some funny pictures! What is Test-Driven Deployment?

  6. geekbay says:

    it’s maybe not directly related with TDD, but with TDD, i agree that you will have a more robust code since it’s tested but finally doesn’t it make development cycle longer since you have to write two codes, one for test and one for the “real” code ? (and if it’s longer, does it really worth it ? since longer mean that the cost of development will be higher too?)
    And my second question, ok so you have some tests, but maybe you have bugs in the test himself, and it can pass but maybe you are not testing the right thing, so my second question is in short, how do you know that you have tested enough or that you don’t have bugs in the test ?

    • Brainwaves says:

      Nice question, was wondering this my self

    • Sawyer says:

      I suggest we create a test of the test to make sure that the test passes its own test, and maybe even another test of the test of the test, this way we triple-make sure that the original code isn’t buggy, and double-make sure that the own test of the original code isn’t buggy, and simply make sure that the test of the test itself isn’t buggy, but there’s still some probability that the test of the test of the test of the original code might contains some bugs… arrggghhh… -_-

    • Scriptin says:

      1. TDD helps to save the time that you’d probably waste on:
      a. spotting bugs;
      b. repairing the system after crashes caused by unspotted bugs – that is crusial when you develop some commertial apps. Your clients might be upset, you know.

      So, even if you spend much time on testing, you save the money, so the costs will be lower. Anyway, I don’t think it takes much time to write tests.

      2. Tests, as you can see in the example of guestbook, are simplier and smaller than actual code, so it’s not so hard to make it right. And, of course, you’ll probably extend your test in the development process, to make them cover all possible bugs.

    • Scriptin says:

      I can say eben more about 2nd question. You actually test each new test itself at least twise:
      1. When you just wrote a new test, it should fail – that’s the negative testing
      2. When you finish writing the actual code, test should pass – this is correct if both test and code are correct, or both wrong in some complicated way (errors complement each other). The probability of accidental complementarity (?) of two bugs is reasonably low.

      • Author

        Hi geekbay,

        You have a point – most companies tend to not use TDD since most developers say that it will almost double development time. The problem is most companies also don’t realize that time spent on TDD is time saved in the future. The only solution here is to really explain it the client that this will actually SAVE them money rather than waste it.

        As for your second question, what I do is test functions at the lowest level. It makes your tests simpler, and at the same time makes you’re able to test your code from the core and not just the higher-level functions.

    • EllisGL says:

      There’s a PHPUnit compatible tool that will help you test for all sorts of issues – I can’t remember the name, but it morphs the expressions to make sure things do fail.

    • flyingfox says:

      It is true, that for really simple projects TDD can be an overkill.

      But…
      First question:

      In my opinion TDD has its biggest benefit in code maintenance and extendability. An example: When you code a commercial website it is likely that you want it up and running for quite a few years. If so, it is almost certain, that business growth or market changes will force you to enhance or adapt your program to meet the new requirements.

      Now, what if you haven’t looked at that code for three years? Will you be able to understand right off, what you have done back then? I have experienced quite a few times, that when looking at my own code only six month later, it almost looks like foreign code to me, because my coding style has improved, i changed the framework or, most likely, i am just out of this project and don’t remember any details or hidden traps anymore.

      So when i have to change that old code, i am scared of breaking it. My mind is not free to create good code then, It is more likely that i am trying to talk my client out of those changes, actualy hurting his business – very bad!

      If my code is tested though, and i trust my tests, i don’t have to understand all the plumbing work i did under the hood back then. I just make my adjustments to the code and run it against my set of tests. If it passes, i know i haven’t broken any of the old code.

      It is the maintainability of code that makes TDD so valuable. You invest time now to get a product that you can use, change, enhance and reuse for years.

      Second question:
      Yes you can have bugs in your tests or just poorly written test code, but then you are likely to write poor code anyway because you haven’t wrapped your mind around the problem. TDD forces you to THINK about your code. When you write a test before you write the code you ask yourself “What does my piece of code have to achieve. What is it’s real and sole purpose?” If it’ more than one purpose you expect it to achieve, it’s not a UNIT. So you break it down into smaller problems until you have isolated one single simple task your code has to do. THEN you write a very simple test, to check this task (very easy to produce bug-free). Then you write your code (The MINIMUM of code to pass this specific simple test).

      The result is loosely coupled, reusable, nicely refactored and LEAN code. TDD makes you a better programmer.

      TDD ia not the holy grail, but it think it can lift you on very high professional level.

    • Danny says:

      Geekbay,

      First, you really should not consider TDD as twice the work. What you gaining from doing TDD is that

      (a) it causes you to think about the problem without thinking about how you are going to implement the code. You are forced to consider WHAT the result should and should not be, without worrying about the HOW (until you need to).

      (b) This testing also serves as a safety net for you and other developers. You can make changes to the code and instantly check to see if you messed something else up (regression testing)…a real confidence boost for someone looking at someone elses code.

      (c) The tests automatically serve as a form of living documentation to your program. — I would not say any of this is a waste, but actually saves time in the long run and a must for anyone who looks at their coding as a craft.

      (d) Not mentioned in the article…I would argue that the point made in step2 “View” is the wrong approach. It is generally viewed as a better design methodology to write the tests with code that seems natural (without considering if you are going to use that array) so that the tests define how the code is written. This lends itself to writing code that seems intuitive rather than contrived.

      Second, regarding knowing how many tests to write: If you think about it as most initially do, that you have to consider all the possibilities to cover your implementation, you kinda miss the point. The brilliance here is that you DO NOT consider your code first. You write tests to define the bounds of the “concept” like, say, a stack. You would write tests to instantiate a stack (test to see if it exists), push an element onto the stack (test that element is the top element on the stack), to pop an element off the stack (verifying that the elemetn on the top of the stack is the one that was under the one just popped….as well as checking for count of items on the stack, isEmpty, etc, etc., for example:

      [example psuedocode]
      Stack famousPeople= new Stack();
      assertTrue(famousPeople.count=0);

      famousPeople.push(“John”);
      famousPeople.push(“Ringo”);
      famousPeople.push.(“George”);
      assertTrue(famousPeople.count=3);

      assertTrue(famousPeople.top=”George”);
      famousPeople.pop();
      assertTrue(famousPeople.count=2);
      assertTrue(famousPeople.top=”Ringo”);

      etc

      Then, you write the MINIMAL code you need to make the tests pass, no more.

    • Danny says:

      Crimeny….just realized I was replying to an old post…..sorry. Well, the points are still valid and hope it helps someone reading the article for the first time!!.

  7. Great article. Thanks.

  8. Pau Gay says:

    Great tutorial. I listened about TDD before but now, it’s much clear. The SimpleTest framework seams good.

    Thanks!

    • Author

      Yeah, SimpleTest is great for fast test creation. A lot of people swear by PHPUnit though, and personally, it’s my go-to Unit Testing Framework as well.

      For smaller projects, SimpleTest should suffice. For more complex testing though, PHPUnit is the way to go.

  9. jan says:

    It’s a pretty good beginners guide to TDD, but the code could have been structured a a lot better. A good rule in TDD is to have only 1 assert in each test. So instead of having a test named testViewGuestbookWithEntries you should have made smaller test like ‘When_Entries_In_Guestbook_Count_Should_Be_Greater_Than_Zero’ ect

  10. David Singer says:

    You should do a tutorial on Rails testing. Its much simpler and more flexible than the PHP testing suites. You can also build testing into your deploy processes so its impossible to go live with code that fails testing.

  11. Shawn says:

    I’ve always found tdd to be a bit of a pain when it comes to developing with a CMS. Great article though.

  12. Michael says:

    I totally agree with this tut! Thanks for it! I actually just spent an internship doing this on the corporate level, and have been trying to find ways to incorporate it into my own work. I’ve also been looking at the Selenium testing suite…but that’s more for testing the front-end of sites. Might be something else to look at, or even do a tut on!

    Thanks again!

    • Author

      Yes, you’re correct. Selenium mostly tests high-level functionality – most of it at the browser level. These testing frameworks can usually test at the lower-level, up to the core functions of an application. Best case scenario is to mix both, but not always ideal time-wise.

  13. Jaspal Singh says:

    Great tutorial.
    Thanks for sharing.

  14. arieh says:

    SimpleTest is PHP4 compatible. I simply can’t see why, after 6-7 years of PHP5, one would still touch a tool that keeps itself that much behind.
    PHPUnit is not hard to use. It is actually very easy to use, specifically compared to the above examples, which are almost the same as with SimpleTest.
    Also, one of the key benefits IMO of TDD is to separate PHP dev from the browser apart from developing your views.
    I’m not a linux user, and I’m certainly much more comfortable at a windowed environment, but being able to run hundreds of tests without the overhead of refreshing a page is an extreme benefit, and it takes only a few minutes to get used to console TDDing.

  15. Ryan Allen says:

    If you’re interested in TDD, straight from the horses mouth, you should totally check out “Test Driven Development by Example” written by Kent Beck. He is the master:

    http://books.google.com.au/books?id=gFgnde_vwMAC&dq=test+driven+development+by+kent+beck&printsec=frontcover&source=bn&hl=en&ei=UCNqTOVNkKNxsZaMzAE&sa=X&oi=book_result&ct=result&resnum=4&ved=0CCoQ6AEwAw#v=onepage&q&f=false

    Listening to Jan above, yes there are a bunch more guidelines to testing that cannot be covered in a single tutorial, but the whole method (and more importantly, the method of thinking) is guided through Kent’s book.

    He is master. Read!

  16. Codeforest says:

    First, it looked like a waste of time to me. But then I realized that it is the best way of coding w/o errors.

    Great article

  17. Daniel says:

    Great tutorial on Code Testing. Never saw a more readable tutorial than this one.
    Great introduction. Very easy to understand.
    CakePHP has an very easy integration to SimpleTest. Even the testcases are baked by the console. Ok, you probably never need the baked ones, but hey – it works ;)

    Great Work1

  18. nice article!
    I will be very useful

  19. harly says:

    Nice post,Test-driven development (TDD), also called test-driven design, is a method of software development in which unit testing is repeatedly done on source code. The concept is to “get something working now and perfect it later.” After each test, refactoring is done and then the same or a similar test is performed again. The process is iterated as many times as necessary until each unit is functioning according to the desired specifications. Test-driven development is part of a larger software design paradigm known as Extreme Programming (XP). Thanks for share with us.

  20. Simon says:

    Nice article !
    TDD is time consuming as hell but at least you’re always sure that everything is working as expected. Very nice when you’re doing some upgrades.
    But PHPUnit should always be used WITH Selenium. Even if something is working backend, it may be broken on the frontend. You can easily test ajax or other javascript with Selenium.
    Hope this will be covered in another article :)

  21. Why waste time on writing up tests? That was my first thought when I joined a team of developers practicing TDD. It does take time only in the beginning. Once you get into it, writing tests will be easy, and benefits will be enormous, especially if there are several people working on the same project.

  22. Adam Leonard says:

    I’ve been awaiting a good tutorial for Unit Testing in PHP. It’s something I don’t do too much in PHP, but Ruby yes. I hope to see more people writing tests for their PHP code!

  23. deerawan says:

    nice article about TDD. I’ve been using PHPUNIT for supporting all my projects.

    Thank you.

  24. Pexeto says:

    I have used TDD while creating some of my projects and I think this makes the code very well structured and easy to maintain. In the beginning it’s a bit hard to get used to it but it’s worth the efforts :)

  25. Thanks for sharing us thet tips it was very very reliable and helpful to us.

  26. Kris says:

    Very nice tut and extremely easy to read.

    TDD is something I learned in my Java classes, but have yet to incorporate it into my PHP dev work, since I had no training. Seems simple enough after reading your article though – - Thanks!

  27. Evan says:

    “Screw it, just move it to production!” This is also known as the Bill O’ Reilly. “F* it! We’ll do it live! I’ll write it and we’ll do it live.”

  28. Hi
    I found this site through search engines.
    Test-Driven Development – Very interesting and useful topic.
    Great Post.Love It.

    The Winnipeg Painters – The Best House Painting Contractors In MB – We offer complete interior painting and exterior painting services for both residential and commercial locations. House painters Winnipeg, MB / Manitoba are the best.

    http://www.thewinnipegpainters.com/

    THANKS

  29. Hi
    Thanks for the wonderful post. I like this as it helped me a lot and sorted my problem. I appreciate the

    work.Enjoyed it.

    The Best FREE Foreclosure Investing Courses And Information Online. FREE Information On Foreclosure

    Investing And Short Sale Deals.
    http://www.freeforeclosureinvestingcourses.com/

    Thanks

  30. Wow! This is useful information! I’m glad that I found this article!

  31. buonzz says:

    wishing there is also a TDD version for Browser Compatibily testing, it’s a really killer one, given the vast number of devices that loads your web pages,

  32. Dexter0015 says:

    Thank you !

    For some time now I’m looking for switch to TDD programming and I hope I will find some great resources on the net like your article, simple and helpful.

    Too often I was confronted to the same problems you talked about because everybody want to go in production ASAP. Now it’s time to be more professional and do best testing. Maybe I will lost some hours at the beginning, but at the end, i’m sure that I will stop wasting my time on little things.

  33. Anele says:

    In my opinion I just think its time consuming to to all these tests….

    Secondly I just started a new job and now i am having to do Unit test on Components on a Rest/JSON Webservice, to check if the returned values are the same as the expected. I am using cakePHP.

    I mean If you are seeing the results on a browser (i.e all connection. classless, functions, helpers. etc) why do a unit test?..
    Anyhow My test is not returning any passes just saying 1 test case complete

    //Import the Component to be tested
    App::import(‘Component’, ‘Wsapi’);

    class WsapiComponentTest extends CakeTestCase{

    function TestComponenTest(){
    $this->WsapiComponentTest = new WsapiComponent(); //Declare a new component test jus to see if any error occor
    }

    function CountriesBranchesFind(){
    $this->Countriesbranches->recursive = 0;
    $results = $this->Countriesbranches->find(‘first’);

    $expected = array (‘ ‘ => array(
    ‘branch_id’ => “”,
    ‘branch_code’ => “”,
    ‘branch_name’ => “”,
    ‘branch_address’ => “”
    ));
    $this->assertFalse($results, $expected);
    $Countriesbranches = json_decode($this->Wsapi->countries(0), true);
    }

    }

  34. chris says:

    did any of you guys got these types of errors?

    Strict Standards: Non-static method SimpleTestCompatibility::isA() should not be called statically, assuming $this from incompatible context in C:\xampp\htdocs\tdd1\test\simpletest\simpletest.php on line 112

    Strict Standards: Non-static method SimpleTestCompatibility::isA() should not be called statically, assuming $this from incompatible context in C:\xampp\htdocs\tdd1\test\simpletest\simpletest.php on line 112

    Strict Standards: Non-static method SimpleTest::isIgnored() should not be called statically, assuming $this from incompatible context in C:\xampp\htdocs\tdd1\test\simpletest\test_case.php on line 614

    Strict Standards: Non-static method SimpleTest::_getRegistry() should not be called statically, assuming $this from incompatible context in C:\xampp\htdocs\tdd1\test\simpletest\simpletest.php on line 132

    Are these normal?

  35. Antonio says:

    Great post. Would be great if tuts plus could do this for rails though :)
    Thanks

  36. daGrevis says:

    Thanks for this article… never knew how TTD actually works, but after reading this article… I have a clue and it’s time to start write tests for my own applications! :)

  37. Willian says:

    What about baby steps?

  38. Gastón says:

    It was time to begin to write more “high level” tuts!

    Great job. Thanks ;)

  39. Marko says:

    A better practice would be to start with Behaviour Driven Development or Specs as a replacement for Unit testing. The reason for this is unit testing using asserts drives you to testing the implementation, for instance:
    $this->assertIsA($entries, ‘array’);
    We don’t really care if $entries is an array or a hash or a proxy object. We care that we can have multiple entries, we care that it behaves like an array.

    http://www.phpspec.net/

    Is a good start.

    For higher level tests, like integration or acceptance tests you could use cucumber http://cukes.info/ (which is in ruby, so you need to code some of your steps in ruby) or you could use cuke4php. https://github.com/olbrich/cuke4php

  40. Stefan says:

    Wow, thanks for this. I usually spend (or should I now say waste?) hours upon hours testing code, specifically in PHP.

    I was wondering, could you recommend me something similar to SimpleText but for Java? Thanks.

  41. ymapefpb says:

    iC1qu, http://www.stargold4u.com/forums/index.php?topic=62532.0 clonazepam presentacion, wU7io, zC9tzdscvc, http://gb-latino.com/foro/index.php?topic=2568.0 rivotril tropfen, rcrkc, qyuxx062P4vV, reductil banned, 633E0vY, reductil weight loss tablets, 676D2yU

  42. Fery Ardiant says:

    Nice post dud,,,

    great job, thanks!

  43. David says:

    Did a kid write this tutorial? ^o)

  44. avaajxpkon says:

    на продажу музыкальную аппаратуру

  45. I like such testing. It takes more time but will check the quality of the product design is good or not

  46. ClovolaKace says:

    c v i 4 2 http://www.lxsoundclips.com/uprofile.php?UID=726 Buy Prosentials q n n 6 8

  47. Timothy says:

    Hey Nick, thanks for the amazing tuts!
    Where should i put the guestbook_test.php in my Zend framework?
    You also said “To run your test, simply run guestbook_test.php in your browser.”, what url would i point the browser to?

    Thanks!

  48. pletchersiz says:

    Hi Ashley, the first drop of the new AW12 Collection will be available in a couple of weeks time – you can see what’s going to arrive in the ‘Coming Soon’ section on uk mulberry bags. More of the collection will launch throughout June and July! Love, Mulberry.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.