Test-Driven Development in PHP: First Steps
videos

Test-Driven Development in PHP: First Steps

Tutorial Details
  • Subject: TDD
  • Difficulty: Intermediate
This entry is part 3 of 12 in the Test-Driven PHP Session
« PreviousNext »

Let’s admit it: the PHP community has lagged a bit, when it comes to advocating test-driven development. We know we should, but, even to this day, a sizable portion of the community does not. In this new series of videos and tutorials, created by the Nettuts+ team, we’re hoping to change that.

Trust me: it’s not as tough as you think.


Lesson 1 – Setup

In this series, we’ll be using Composer, a dependency manager, to install PHPUnit (or at least, the unofficial version for now). To ensure that we’ve installed it properly, we’ll also create a quick calculator test and class.

Choose 720p for the clearest picture.

Show Links

Tags: Videos
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://dankruse.com Furley

    Great tutorial. You timing is great. I enjoy that you assume an intermediate level of knowledge and move quickly.

    Composer is great as well.

  • http://zando.co.uk alex

    Link is wrong for composer, should be .org not .com

  • Pieter

    I started feeling guilty that I wasn’t doing tests just this week, so this article comes in so handy!

  • Mike

    Great timing!

    Was just thinking about how I was going to expand current phase of project to improve stability. Well the answer is simple — PHPUnit.

    Thanks as usual!

  • Prabhjeet Singh

    Great! now I got how to use these things practically. Thanks

  • Devin Dombrowski

    PHP can be so awesome and powerful. It’s almost sad that it’s not the “cool” language any more, though it has made some nice leaps lately. Any way, my point is,…. It’s a shame that phpUnit is stuck on PEAR.

    Thanks Jeffrey (et al.) for this series

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Somebody will officially add Composer support pretty soon.

      PHP may not be the most trendy or beautiful language, but frameworks like FuelPHP and Laravel show that you can write some extremely expressive code with it.

      • http://wouterj.nl Wouter J

        You don’t want to get PHPunit on Composer, do you? Don’t get this wrong, Composer is great, but Composer is for loading dependencies inside your project.
        This should be globally on your system and should not be included in every single project. That’s why I agree with the PHPunit staff and why I wouldn’t see PHPunit as a package.

      • http://johnnyfreeman.us Johnny Freeman

        @Wouter J – I have to disagree. I have many projects on my system, some of which are a few years old. And if my PHPUnit was global, I would have to keep my tests for old projects updated too, which doesn’t make sense from a business perspective. By using PHPUnit as a dependency inside my project, I can avoid that and only update those tests when I make a change to the actual project.

        In other words, tests are _dependent_ on a specific version of PHPUnit when they are created, so it doesn’t make sense for it to be global. Same reason is doesn’t always make sense for Composer to be global. Or a framework core to be global. :)

        Having said that, if you have a machine where all projects are in active development, yes, it makes more sense for PHPUnit to be global (and composer).

    • http://digitale-avantgarde.com chp

      Here is a flaming pro on PHP by symfonyies lead architect:

      http://fabien.potencier.org/article/64/php-is-much-better-than-you-think

  • samir

    something about MVC IN PHP AND MYSQL (PDO may be)?!
    thank you jeff

  • http://jasoncalliero.com Jason Calleiro

    What VIM colorscheme are you using? Great intro to testing in PHP btw.

  • http://www.lollypop.gr/en G.Drakakis

    Once again an amazing screencast. I am a huge fan of yours, Jeffrey.

  • Michael

    An article called “Test-Driven Development in PHP” should focus more on TDD instead of things like composer and packagist…

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      It’s the first installation lesson. All future lessons in the series will focus on the code.

  • http://wouterj.nl Wouter J

    I hope you are going to talk about the phpunit.xml.dist file, which is very usefull. Also if you use namespaces it is good to use different directories in the test directory. The class MyApp\Calculator\Calculator has a test in tests\MyApp\Test\Calculator\CalculatorTest.php. You need to give your test class the namespace MyApp\Test\Calculator.

    I’m also not a huge fan of TTD. Why do we need to run a test if we already know it is wrong? A test needs to be a check to see if everything works as expected. If we use an add method in our test and don’t add it to the calculator class, why do we need to run the test? The test shall give an error, we need to write the add method and then we need to run the test again and see it is right.
    I test everything, but not with TTD, with Unit tests and Functional Tests.

    • Patkos Csaba

      When you do TDD, you have to write a failing test before code. If you don’t run the test, how can you be sure it fails?

      You may say: “Well, I just wrote a test for a method that doesn’t exist, it will surely fail.” And, most of the cases you may be right. But, at the same time, you wrote a test for an inexistent method which made you to think about your future method from the perspective of the client of you class. This is important, very important.

      Plus, when you work on in a team, on code written by someone else, you may very well write a test for a method you think is not there … but it may be there in a parent class without you knowing it. Running the test assures you that you are on the right path to solve the problem.

    • Richard

      The reason you don’t see the benefit of testing first is because you don’t understand TDD so I recommend you search the Internet for more resources on it.

      Before you ever great a new class or method you should always write the test before hand. Your tests can serve as specs for what the method or class should return or do. If you write the class or method first you’re just going to cheat yourself and write lousy tests just to get them to pass. Testing first forces you to write good, honest tests.

  • Greg

    Great tut Jeff, Thanks!

    Have you moved back to Vim from Sublime Text?

  • Patkos Csaba

    The presentation is great. A very nice introduction to TDD on PHP. However, I would like to make an observation.

    When you implemented the “subtract” method, you made these steps:
    - expect a correct result for a subtraction
    - there was an error because the method did not exist
    - there was a failure when the method existed but there was no logic
    - then finally the test passed
    This is an Error – Fail – Pass cycle pretty strongly opposed in the TDD community. You should never rely on the fact that a test changes from Error to Fail. There can be any number of reasons to get an Error instead a Fail or vice versa.

    There are several option to avoid this:
    - make a test expecting null -> Error -> make a method returning nothing -> Pass -> modify test test expecting correct result -> Fail -> implement logic -> Pass
    - or if the logic is simple enough, you can write a test for a new method and than create the method and it’s implementation as one single step.

  • http://vamsii.com Vamsi

    Good initiative .. also do look at BDD in PHP.. ( Behat )

  • http://akmwebtech.in awebtech

    Nice tutorial, very few developers use php testing tool. but you explained well

  • https://github.com/Maher4Ever Maher Sallam

    To automatically run your PHPUnit tests when changes happen, you could use Guard::PHPUnit (https://github.com/Maher4Ever/guard-phpunit). It’s very simple to use and it’s comes with a custom printer to make it’s printed results prettier.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Yep – that’ll be covered in one of the next lessons.

  • Patrick

    I was own my way to dig myself right into it and than you create this great tutorial! Exactly what I need to start!!! Thanks and hopefully there will be further tutorials on this topic

    Bye

    Patrick

  • http://gadgetcritiques.com/ Jesslyn

    Thanks for the useful tutorial, Jeff! :) I was thinking of how to use the PHP Unit..this tutorial really came at the right time..should I say it is the Law of Attraction%sF

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Thanks, Jessyln. There will be many more on the subject, so stay tuned.

  • http://zaizaizaizai.com damn

    “Tutorial” starts at 08:00

  • Todor Pavlov

    I find RSpec-like testing a lot easier to use than PHPUnit. The best ones in PHP world that I found are:
    1. Pecs – https://github.com/noonat/pecs
    2. Spectrum – https://github.com/mkharitonov/spectrum/

  • Marcio Almada

    Jeffrey, congrats, a lot of good series starting recently here on Nettuts. Can’t wait to see PHPUnit and database interactions.

    • Kevin

      Love to see it as well!

    • Richard

      I’m a bit confused by this. If you build your code correctly (decouple your models and persistent data storage) you should be able to run your Unit tests without connecting to the database.

      • Patkos Csaba

        Correct. Unit testing with databases should never happen. Even more, Active Record works so well these days that I wrote no SQL query for more than a year now.

  • http://websourcefree.com saha

    Nice tutorial. Thanks for this useful tutorial.

  • Egor

    What terminal application is used in video?

  • http://feed2.me David

    What did you do to make it automatically include the PHPUnit class?

  • http://www.interlacelab.com Nj

    I’ll have to start using this as part of my development process.

  • Ian

    Hi Jeffrey,

    I have that love/hate relationship with PEAR. For me it’s caused by PEAR always being a major pain to get anything installed whether on Linux or Windows. So I was hoping Composer would just be easy.

    First thing, I got an error running the curl command to download composer.phar
    Parse error: syntax error, unexpected $end in – on line 255

    I’m thinking that may be a curl issue but the error is not very helpful.

    So I went back to trying to get phpunit working and after much messing around finally got it up and running with PEAR for the first time ever (and I’ve tried many times in the past).

    Then I saw that I can just download the composer.phar file manually. So I got it and tried using a .bat file since I’m on Windows but can’t get it to work like phpunit does. For phpunit I put phpunit.bat in a directory on my system PATH and it just works. So I tried the same with composer by making a .bat file and putting it along with composer.phar in the System32 directory and I just get a error “unable to open the file composer.phar” . I was a little confused how you are running composer without running it through php and I tried adding “php composer.phar” to the bat file but that doesn’t work either. How are you running it without using php anyway? Does Mac by default know how to read and run a .phar file without php?

    Well, either way, I can run it from my test dir with php composer.phar and I can run phpunit now so will the rest of the course be strictly phpunit so I can just use which ever one works best for me?

    Thanks for the lesson. Even with the frustration it’s fun to learn these things and I like making them work on Windows.

    • ian

      Just remembered to come back and post, I found the issue on Windows was line 255 in the installer php file. It’s the installer code throwing the error. Composer it’s self works fine once it’s downloaded manually. Also figured out this line “#!/usr/bin/env php” at the top of the composer file is why you don’t have to type ‘php’ before composer when you put the file in your system path. The issue with running a bat file is paths on my system because now I can run it through a bat file but when I do, composer can’t find Phar so it’s just a matter of making sure I’ve got everything set up with the system paths correctly.

      Anyway, can’t wait to go through the next tutorial on this.

  • http://thedeeperweb.tumblr.com/ Marcel

    Great video, love the speed at which the tutorial is going.

    Well, I work with CakePHP which comes with PHPUnit already integrated.

    It makes testing your models, views and controllers very easy,
    and a web interface provides an overview of each of your classes tests.

    Can only recommend that.

  • http://defaulttricks.com Mohit Bumb

    Thanks for source codes

  • ken

    Nice One waiting for Part 2 ??

  • camp

    Next lesson?

  • me

    Youtube is blocked here. Is the video also posted somewhere else?

  • http://jerrylclark.angelfire.com/ Harlan Fox

    The PHP community has lagged a bit, when it comes to advocating test-driven development.

  • ScottLesovic

    If you didn’t notice, Sebastian has officially included PHPUnit in Composer: https://packagist.org/packages/phpunit/phpunit

    test-runner file is located:

    vendor/phpunit/phpunit/composer/bin/phpunit

  • marketing

    I’m researching this
    kind of matter to use in a very long term business I will be thinking about
    beginning. Appreciate this information, it has been academic and also helpful
    to us.
    Prospecting

  • Preston Davis

    I’m on Win7/64 + WampServer 2.2 and right up front (at install) I ran right into a WARNING MESSAGE stating that “the openssl extension is missing”. So I aborted the install and enabled php_openssl in wamp and verified that it is uncommented in php.ini, but I’m still getting the same WARNING MESSAGE.

    So now I do not know whether to continue anyway (cuz I have not used openssl) or Abort because it will make Composer unstable. Any advice?

    Preston