smallseo.info

phpunit

The PHP Unit Testing framework. PHPUnit – The PHP Testing Framework

SimpleTest vs PHPunit

I was wondering if anyone that have experience in both these stuff can shed some light on the significant difference between the two, if any?

Any specific strength of each that makes it suitable for any specific case?


Source: (StackOverflow)

How do I use PHPUnit with CodeIgniter?

I have read and read articles on PHPUnit, SimpleTest, and other Unit Testing frameworks. They all sound so great! I finally got PHPUnit working with Codeigniter thanks to https://bitbucket.org/kenjis/my-ciunit/overview

Now my question is, how do I use it?

Every tutorial I see has some abstract use like assertEquals(2, 1+1) or:

public function testSpeakWithParams()
{
    $hello = new SayHello('Marco');
    $this->assertEquals("Hello Marco!", $hello->speak());
}

That is great if I had a function that would output such a predictable string. Usually my apps grab a bunch of data from the database then display it in some sort of table. So how do I test Codeigniter's controllers?

I would like to do Test-Driven Development and I have read the tutorial on PHPUnits site, but once again the example seem so abstract. Most of my codeigniter functions are displaying data.

Is there a book or a great tutorial with a practical application and examples of PHPUnit testing?


Source: (StackOverflow)

phpunit avoid constructor arguments for mock

What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The api seems to be like this:

getMock($className, $methods = array(), array $arguments = array(),
        $mockClassName = '', $callOriginalConstructor = TRUE,
        $callOriginalClone = TRUE, $callAutoload = TRUE)

I don't get it to work. It still complains about the constructor argument, even with $callOriginalConstructor set to false.

I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.


Source: (StackOverflow)

Autoloading classes in PHPUnit using Composer and autoload.php

I have just installed PHPUnit version 3.7.19 by Sebastian Bergmann via Composer and have written a class I would like to unit test.

I would like to have all my classes autoloaded into each unit test without having to use include or require at the top of my test but this is proving to be difficult!

This is what my directory structure looks like (a trailing / slash indicates a directory, not a file):

  • composer.json
  • composer.lock
  • composer.phar
  • lib/
    • returning.php
  • tests/
    • returningTest.php
  • vendor/
    • bin/
      • phpunit
    • composer/
    • phpunit/
    • symfony/
    • autoload.php

My composer.json file includes the following:

"require": {
    "phpunit/phpunit": "3.7.*",
    "phpunit/phpunit-selenium": ">=1.2"
}

My returning.php class file includes the following:

<?php
class Returning {
    public $var;
    function __construct(){
        $this->var = 1;
    }
}
?>

My returningTest.php test file includes the following:

<?php
class ReturningTest extends PHPUnit_Framework_TestCase
{
    protected $obj = null;

    protected function setUp()
    {
        $this->obj = new Returning;
    }

    public function testExample()
    {   
        $this->assertEquals(1, $this->obj->var);
    }

    protected function tearDown()
    {

    }
}
?>

However, when I run ./vendor/bin/phpunit tests from the command-line, I get the following error:

PHP Fatal error: Class 'Returning' not found in /files/code/php/db/tests/returningTest.php on line 8

I noticed that composer produced an autoload.php file in vendor/autoload.php but not sure if this is relevant for my problem.

Also, in some other answers on Stack Overflow people have mentioned something about using PSR-0 in composer and the namespace command in PHP, but I have not been successful in using either one.

Please help! I just want to autoload my classes in PHPUnit so I can just use them to create objects without worrying about include or require.


Update: 14th of August 2013

I have now created an Open Source project called PHPUnit Skeleton to help you get up and running with PHPUnit testing easily for your project.


Source: (StackOverflow)

phpunit mock method multiple calls with different arguments

Is there any way to define different mock-expects for different input arguments? For example, I have database layer class called DB. This class has method called "Query ( string $query )", that method takes an SQL query string on input. Can I create mock for this class (DB) and set different return values for different Query method calls that depends on input query string?


Source: (StackOverflow)

How to Read / Improve C.R.A.P Index Calculated by PHP

I just started working with PHPUnit and its colorful code coverage reports. I understand all the numbers and percentages save one: The C.R.A.P index. Can anyone offer me a solid explanation of what it means, how to analyze it and how to lower it?


Source: (StackOverflow)

How to set up database-heavy unit tests in Symfony2 using PHPUnit?

I am quite new to the world of testing and I want to make sure I am on the right track.

I am trying to setup unit tests in a symfony2 project using phpunit.

PHPUnit is functional and the simple default controller tests work fine. My project relies heavily on database interactions though, and as far as I understand from phpunit's documentation, I should set up a class based on \PHPUnit_Extensions_Database_TestCase, then create fixtures for my db and work from there.

Yet, symfony2 only offers a WebTestCase class which only extends from \PHPUnit_Framework_TestCase out of the box.

So am I right to assume that I should create my own DataBaseTestCase which mostly copies WebTestCase, only difference being that it extends from \PHPUnit_Extensions_Database_TestCase and implements all its abstract methods?

Or is there another "built-in" recommended workflow for symfony2 concerning database-centric tests?

As I want to make sure that my models store and retrieve the right data, I do not want to end up testing the specifics of doctrine by accident.


Source: (StackOverflow)

Mock in PHPUnit - multiple configuration of the same method with different arguments

Is it possible to configure PHPUnit mock in this way?

$context = $this->getMockBuilder('Context')
   ->getMock();

$context->expects($this->any())
   ->method('offsetGet')
   ->with('Matcher')
   ->will($this->returnValue(new Matcher()));

$context->expects($this->any())
   ->method('offsetGet')
   ->with('Logger')
   ->will($this->returnValue(new Logger()));

I use PHPUnit 3.5.10 and it fails when I ask for Matcher because it expects "Logger" argument. It is like the second expectation is rewriting the first one, but when I dump the mock, everything looks ok.


Source: (StackOverflow)

Can I "Mock" time in PHPUnit?

... not knowing if 'mock' is the right word.

Anyway, I have an inherited code-base that I'm trying to write some tests for that are time-based. Trying not to be too vague, the code is related to looking at the history of an item and determining if that item has now based a time threshold.

At some point I also need to test adding something to that history and checking that the threshold is now changed (and, obviously, correct).

The problem that I'm hitting is that part of the code I'm testing is using calls to time() and so I'm finding it really hard to know exactly what the threshold time should be, based on the fact that I'm not quite sure exactly when that time() function is going to be called.

So my question is basically this: is there some way for me to 'override' the time() call, or somehow 'mock out' the time, such that my tests are working in a 'known time'?

Or do I just have to accept the fact that I'm going to have to do something in the code that I'm testing, to somehow allow me to force it to use a particular time if need be?

Either way, are there any 'common practices' for developing time-sensitive functionality that is test friendly?

Edit: Part of my problem, too, is the fact that the time that things occurred in history affect the threshold. Here's an example of part of my problem...

Imagine you have a banana and you're trying to work out when it needs to be eaten by. Let's say that it will expire within 3 days, unless it was sprayed with some chemical, in which case we add 4 days to the expiry, from the time the spray was applied. Then, we can add another 3 months to it by freezing it, but if it's been frozen then we only have 1 day to use it after it thaws.

All of these rules are dictated by historical timings. I agree that I could use the Dominik's suggestion of testing within a few seconds, but what of my historical data? Should I just 'create' that on the fly?

As you may or may not be able to tell, I'm still trying to get a hang of all of this 'testing' concept ;)


Source: (StackOverflow)

Difference between assertEquals and assertSame in phpunit?

PHPUnit contains an assertEquals method: https://phpunit.de/manual/current/en/appendixes.assertions.html#appendixes.assertions.assertEquals

It also has an assertSame method: https://phpunit.de/manual/current/en/appendixes.assertions.html#appendixes.assertions.assertSame

At first glance it looks like they do the same thing. What is the difference between the two? Why are they both specified?


Source: (StackOverflow)

PHPUnit: CLI output during test debugging possible?

When running a PHPUnit test, I would like to be able to dump output so I can debug one or two things.

I have tried the following (similar to the PHPUnit Manual example);

class theTest extends PHPUnit_Framework_TestCase
{
    /**
     * @outputBuffering disabled
     */
    public function testOutput() {
        print_r("Hello World");
        print "Ping";
        echo "Pong";
        $out = "Foo";
        var_dump($out);
    }   
}

With the following result:

PHPUnit @package_version@ by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.00Mb

OK (1 test, 0 assertions)

Notice there is none of the expected output.

I'm using the HEAD versions of the git repos as of September 19th, 2011.

Output of php -version:

$ php -version
PHP 5.2.9 (cli) (built: Dec  8 2010 11:36:37) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans

Is there anything I'm doing wrong, or is this potentially a PHPUnit bug?


Source: (StackOverflow)

PHPUnit best practices to organize tests

I am currently going to start from scratch with the phpunit tests for a project. So I was looking into some projects (like Zend) to see how they are doing things and how they organizing their tests.

Most things are pretty clear, only thing I have some problems with is how to organize the test suites properly. Zend has an AllTests.php from which loads others test suites.
Tough looking at the class it is useing PHPUnit_Framework_TestSuite to create a suite object and then add the other suites to it, but if I look in the PHPUnit docs for organizing tests in PHPUnit versions after 3.4 there is only a description for XML or FileHierarchy. The one using classes to organize the tests was removed.
I haven't found anything that this method is deprecated and projects like Zend are still using it.

But if it is deprecated, how would I be able to organize tests in the same structure with the xml configuration? Executing all tests is no problem, but how would I organize the tests (in the xml) if I only wanted to execute a few tests. Maybe creating several xmls where I only specify a few tests/test suites to be run?

So if I would want to only test module1 and module2 of the application, would I have an extra xml for each and defining test suites only for those modules (classes used by the module) in it. And also one that defines a test suite for all tests?

Or would it be better to use the @group annotation on the specific tests to mark them to be for module1 or module2?

Thanks in advance for pointing me to some best practices.


Source: (StackOverflow)

How do I correctly install PHPUnit with PEAR?

I have had to de- and reinstall a newer version of PHPUnit following these directions. Now when I'm launching this line

sudo pear install --alldeps phpunit/PHPUnit

I see an error message, that looks like this.

Unknown remote channel: pear.symfony.com
phpunit/PHPUnit requires package "channel://pear.symfony.com/Yaml" (version >= 2.1.0)
No valid packages found

If I install just Yaml by launching

sudo pear install symfony/YAML

an older version (1.0.6) will be installed that doesn't meet the dependency of PHPUnit. How can I possibly solve this?


Source: (StackOverflow)

Test PHP headers with PHPunit

I'm trying to use PHPunit to test a class that outputs some custom headers.

The problem is that on my machine this:

<?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        $headers_list = headers_list();
        header_remove();

        ob_clean();

        $this->assertContains('Location: foo', $headers_list);
    }
}

or even this:

<?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        header_remove();

        ob_clean();
    }
}

return this error:

name@host [~/test]# phpunit --verbose HeadersTest.php 
PHPUnit 3.6.10 by Sebastian Bergmann.

E

Time: 0 seconds, Memory: 2.25Mb

There was 1 error:

1) HeadersTest::testHeaders
Cannot modify header information - headers already sent by (output started at /usr/local/lib/php/PHPUnit/Util/Printer.php:173)

/test/HeadersTest.php:9

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

This looks as if there is something else outputting to the terminal before the test runs even though there is no other file included and there is no other character before the beginning of the PHP tag. Could it be something inside PHPunit that is causing this?

What could the issue be?


Source: (StackOverflow)

phpunit restarting tests randomly

I am trying to test my symfony2 application using PHPUnit. I got one project where everything works as expected, but on my other project I have this strange behaviour that PHPUnit either stops executing the Test Suite randomly near the end of all tests and restarts or restarts the tests after finishing the Test Suite and writing the code coverage. Other times it runs normally.

Here is some output to make visible what is happening ( Test is restarting over and over):

PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
...........PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
...PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
............PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
............PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
..................

Time: 01:03, Memory: 43.00Mb

OK (83 tests, 145 assertions)

Writing code coverage data to XML file, this may take a moment.

Generating code coverage report, this may take a moment.

Here is an example of the Test Suite restarting after executing all tests:

PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
..................

Time: 01:29, Memory: 53.25Mb

OK (83 tests, 145 assertions)

Writing code coverage data to XML file, this may take a moment.

Generating code coverage report, this may take a moment.
PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from C:\workspace\cllctr\app\phpunit.xml

................................................................. 65 / 83 ( 78%)
............PHPUnit 3.6.10 by Sebastian Bergmann.

As my other project runs without any problems, there must be some problem within my code. But I cannot figure out what possibly triggers this behaviour! The logs don't show nothing unexpected/strange.

EDIT

Yesterday, I noticed something strange: I decided to switch from MongoDB to MySQL because of some unrelated reasons. After the transition was done, all tests run without any problems. I tried it many times and I'm not able to reproduce it anymore. As this only happened with my functional tests, I tend to think that the problem was my WebTestCase class, which runs some commands to clear and rebuild the database. Maybe someone who also uses MongoDB can reproduce this behaviour?


Source: (StackOverflow)