PHPUnit extension for database interaction testing.

Related tags

Testing dbunit
Overview

This extension is no longer maintained

DbUnit

PHPUnit extension for database interaction testing.

Installation

Composer

If you use Composer to manage the dependencies of your project then you can add DbUnit as a development-time dependency to your project:

$ composer require --dev phpunit/dbunit

PHP Archive (PHAR)

You can download a PHAR of DbUnit:

$ wget https://phar.phpunit.de/dbunit.phar

The example below shows how to configure PHPUnit to load all *.phar files found in a given directory (tools/phpunit.d in this example):

">
xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.0/phpunit.xsd"
         extensionsDirectory="tools/phpunit.d">
phpunit>
Comments
  • TRUNCATE fails on tables which have foreign key constraints

    TRUNCATE fails on tables which have foreign key constraints

    As of MySQL 5.5 TRUNCATE fails if the table being truncated is referenced by foreign key constraints in other tables.

    A temporary solution appears to be to disable foreign key checks before truncation and then re-enable them afterwards

    http://zendframework.com/issues/browse/ZF-11235?focusedCommentId=45644&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-45644

    stale 
    opened by BRMatt 29
  • Check for simplexml being loaded before calling @simplexml_load_file.

    Check for simplexml being loaded before calling @simplexml_load_file.

    It is a fatal error to call undefined functions. When such calls are preceded with @, php dies without any feedback as to the cause of the error. Add a check for simplexml_load_file's existence before calling it with @.

    opened by p 16
  • PHPUnit_Extensions_Database_DataSet_YamlDataSet getTable and formatting numbers

    PHPUnit_Extensions_Database_DataSet_YamlDataSet getTable and formatting numbers

    I have fixture file

    accounts:
      -
         creditor_account: x
         debitor_account: y
         amount: 5.00
    

    but when I load it using:

    $yamlDataset = new \PHPUnit_Extensions_Database_DataSet_YamlDataSet(
        $pathToFixture
    );
    return $yamlDataset->getTable($tableName);
    

    my test fails because 5.00 gets formated to 5.

    stale 
    opened by Trudko 10
  • Truncate on PostgresSQL does not reinitialize sequences values

    Truncate on PostgresSQL does not reinitialize sequences values

    Running DBUnit with fixtures may cause exceptions to be fired when trying to save new objects to database (for example with an ORM engine like Doctrine) or make asserts fail (especially assertTablesEqual) because of duplicate primary keys or primary keys not the same at each test run-tine. Example with the following:

    <?xml version="1.0" encoding="UTF-8"?>
    <dataset>
        <table name="students">
            <column>stud_id</column>
            <column>stud_name</column>
            <column>stud_surname</column>
        </table>
        <row>
            <value>1</value>
            <value>John</value>
            <value>DOE</value>
        </row>
        <row>
            <value>2</value>
            <value>Jane</value>
            <value>DOE</value>
        </row>
        <row>
            <value>3</value>
            <value>Jack</value>
            <value>DOE</value>
        </row>
    </dataset>
    

    Running the code above may fail with a unique key constraint exception fired by Postgres as Doctrine will try to store a new Student object, using sequence next value whereas a Student already exists in database for the computed stud_id number.

    $objStudent = new Student();
    $objStudent->setSurname('James');
    $objStudent->setName('DOE');
    $objEntityManader->persist($objStudent);
    $objEntityManader->flush(); // Exception may occur here
    

    Same thing with the following:

    $objTableQuery = $this->getConnection()->createQueryTable('student', 'SELECT * FROM student ORDER BY stud_id');
    $objTableExpected = $this->createXmlDataSet(__DIR__ . '/PersistStudent.xml')->getTable('student');
    $this->assertTablesEqual($objTableExpected, $objTableQuery);
    

    having PersistStudent.xml as follow :

    <?xml version="1.0" encoding="UTF-8"?>
    <dataset>
        <table name="students">
            <column>stud_id</column>
            <column>stud_name</column>
            <column>stud_surname</column>
        </table>
        <row>
            <value>1</value>
            <value>John</value>
            <value>DOE</value>
        </row>
        <row>
            <value>2</value>
            <value>Jane</value>
            <value>DOE</value>
        </row>
        <row>
            <value>3</value>
            <value>Jack</value>
            <value>DOE</value>
        </row>
        <row>
            <value>4</value>
            <value>James</value>
            <value>DOE</value>
        </row>
    </dataset>
    

    Here, we cannot figure out if stud_id will be 4 or something else, making assertTablesEqual fail. In fact, it may fail most of the time.

    I'll try to find a fix and post it here.

    stale 
    opened by MaxEvron 9
  • Booleans also must be treated in a special way

    Booleans also must be treated in a special way

    In another pull request it was added a special case for comparing numeric values: https://github.com/sebastianbergmann/dbunit/commit/94e8237bb516889164b40a22da13aaa0c88a0c9f#diff-ff8d2de4c53f9d6000d6c4dbb9c90c34R167

    But the thing is that database driver (PDO pgsql in my case) might also return booleans.

    And since there is no way to specify a boolean value in a fixture file (they all are treated as strings) - the comparison $thisValue !== $otherValue is always evaluated to false.

    stale 
    opened by zerkms 8
  • ArrayDataSet: invalid initialization for mixed rows

    ArrayDataSet: invalid initialization for mixed rows

    I have found out that the same list of columns should be used for all the rows even if this is not strictly needed.

    The problem comes from the constructor of ArrayDataSet. The first row is used to decide which columns are available: https://github.com/sebastianbergmann/dbunit/blob/master/src/Extensions/Database/DataSet/ArrayDataSet.php#L44

    It would be more user-friendly to calculate the union of all the rows keys. And if this is not possible, at least yell during the construction instead of setting silently to null all the remaining columns.

    stale 
    opened by balland 7
  • Bug fix: Fatal error:  Cannot call abstract method PHPUnit_Extensions_Da...

    Bug fix: Fatal error: Cannot call abstract method PHPUnit_Extensions_Da...

    Fixes bug: Fatal error: Cannot call abstract method PHPUnit_Extensions_Database_TestCase::getConnection() in /usr/share/pear/PHPUnit/Extensions/Database/TestCase.php on line 261

    opened by josefzamrzla 7
  • Issue76

    Issue76

    Patch for https://github.com/sebastianbergmann/dbunit/issues/76.

    • merges all rows of all datasets in one mother dataset
    • added tests to ensure that all data is merged in the the mother table.
    • added tests if adding incompatible tables

    Not sure why my previous contribution is still reflected here despite reforking. Must be a github thing.

    opened by jeunito 6
  • CompositeDataSet: Mismatching documentation and implementation

    CompositeDataSet: Mismatching documentation and implementation

    CompositeDataSet's documentation (version 3.7) states that when several datasets contain the same table the rows are appended in the specified order. Subsequently, the code example composes two data sets like this:

    class CompositeTest extends PHPUnit_Extensions_Database_TestCase
    {
        public function getDataSet()
        {
            $ds1 = $this->createFlatXmlDataSet('fixture1.xml');
            $ds2 = $this->createFlatXmlDataSet('fixture2.xml');
    
            $compositeDs = new PHPUnit_Extensions_Database_DataSet_CompositeDataSet();
            $compositeDs->addDataSet($ds1);
            $compositeDs->addDataSet($ds2);
    
            return $compositeDs;
        }
    }
    

    The fixture files contain rows from the same table (guestbook).

    Unfortunately, the code above doesn't work for two reasons:

    • CompositeDataSet()'s constructor expects a (non-optional) array.
    • More severely, the constructor will fail with an InvalidArgumentException: DataSet contains a table that already exists. That's because it iterates over each given data set and verifies that no table is specified more than once (see CompositeDataSet::addDataSet()).

    I verified all of this by modifying the BankAccount sample and returning a composite BankAccountDBTest::getDataSet() which displayed the results outlined above.

    It seems to me that the loop performed in addDataSet() shouldn't be required. I'd also prefer to have setters for data sets (either instead of or in addition to an optional constructor) to allow for them to be passed incrementally.

    opened by timoreimann 6
  • assertTablesEqual() relies on records' order.

    assertTablesEqual() relies on records' order.

    Using PHPUnit-3.5.0 and PHP-5.3.3 on Ubuntu 10.10. Not tested with other versions.

    The following test should not fail because it compares a dataset to itself.

    Here is DatabaseTest.php:

    <?php
    require_once 'PHPUnit/Extensions/Database/TestCase.php';
    require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
    
    class DatabaseTest extends PHPUnit_Extensions_Database_TestCase
    {
      protected function getConnection()
      {
        $pdo = new PDO('sqlite:db/negozi.db');
        return $this->createDefaultDBConnection($pdo, 'negozi');
      }
    
      protected function getDataSet()
      {
        return $this->createXMLDataSet(dirname(__FILE__).'/dati-iniziali.xml');
      }
    
      public function testTableNazione() {
        $set = $this->createXMLDataSet(dirname(__FILE__).'/dati-iniziali.xml');
    
        $this->assertTablesEqual(
          $set->getTable('NAZIONE'),
          $this->getConnection()
               ->createDataSet()
               ->getTable('NAZIONE')
        );
      }
    }
    ?>
    

    Here is dati-iniziali.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE dataset SYSTEM "dataset.dtd">
    <dataset>
      <table name="NAZIONE">
        <column>CODICE_ISO</column>
        <column>NOME</column>
        <row>
          <value>IT</value>
          <value>Italia</value>
        </row>
        <row>
          <value>FR</value>
          <value>Francia</value>
        </row>
        <row>
          <value>SP</value>
          <value>Spagna</value>
        </row>
      </table>
    </dataset>
    

    The output of phpunit DatabaseTest.php is:

    PHPUnit 3.5.0 by Sebastian Bergmann.
    
    F
    
    Time: 1 second, Memory: 3.75Mb
    
    There was 1 failure:
    
    1) DatabaseTest::testNuovoCliente
    Failed asserting that actual 
    +----------------------+----------------------+
    | NAZIONE                                     |
    +----------------------+----------------------+
    |      CODICE_ISO      |         NOME         |
    +----------------------+----------------------+
    |          FR          |       Francia        |
    +----------------------+----------------------+
    |          IT          |        Italia        |
    +----------------------+----------------------+
    |          SP          |        Spagna        |
    +----------------------+----------------------+
    
     is equal to expected 
    PHPUnit_Extensions_Database_DataSet_DefaultTable Object
    (
        [tableMetaData:protected] => PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData Object
            (
                [columns:protected] => Array
                    (
                        [0] => CODICE_ISO
                        [1] => NOME
                    )
    
                [primaryKeys:protected] => Array
                    (
                    )
    
                [tableName:protected] => NAZIONE
            )
    
        [data:protected] => Array
            (
                [0] => Array
                    (
                        [CODICE_ISO] => IT
                        [NOME] => Italia
                    )
    
                [1] => Array
                    (
                        [CODICE_ISO] => FR
                        [NOME] => Francia
                    )
    
                [2] => Array
                    (
                        [CODICE_ISO] => SP
                        [NOME] => Spagna
                    )
    
            )
    
    )
     Reason: Expected value of IT for row 0 column CODICE_ISO, has a value of FR
    
    /home/marcenuc/Tailor/workspace-php/ConfezioniSposo/remote/lib/DatabaseTest.php:26
    
    FAILURES!
    Tests: 1, Assertions: 1, Failures: 1.
    
    bug stale 
    opened by marcenuc 6
  • assertTablesEqual() on an empty YAML generated table

    assertTablesEqual() on an empty YAML generated table

    This worked fine in 3.0.2 but is broken in 3.0.3, we're using phpunit 6.2.4 on PHP 7.0.22-0

    We have an empty table in a YAML file "media_group_download-seed.yml"

    revolution.media_group_download:
    

    We're doing some tests and then at the end we'd like to assert that the table is still empty "test.php"

    $queryTable = $this->getConnection('revolution')->createQueryTable(
        'revolution.media_group_download',
        'SELECT medias_groups_junction_id, user_id, company_id, supplier_id  FROM revolution.media_group_download'
    );
    
    $expectedDataset = new \PHPUnit\DbUnit\DataSet\YamlDataSet(
        __DIR__ . '/fixture/media_group_download-seed.yml'
    );
    $expectedTable = $expectedDataset->getTable("revolution.media_group_download");
    
    $this->assertTablesEqual($expectedTable, $queryTable);
    

    As mentioned above up until version 3.0.2 it worked fine, but now the test fails with the output:

    Failed asserting that
    +----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+
    | revolution.media_group_download                                                                                                                                                                                                                                                                          |
    +----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+
    |          id          | medias_groups_juncti |         time         |       user_id        |      company_id      |     supplier_id      |      license_id      |      downloads       |  project_reference   |       comment        |      education       |         year         |        month         |
    +----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+----------------------+
    
     is equal to expected
    +----------------------+
    | revolution.media_group_download |
    +----------------------+
    
    stale 
    opened by ernst-at-colourbox 5
  • Wanted (Maybe?): New Maintainer

    Wanted (Maybe?): New Maintainer

    A while ago I visited @beberlei at the offices of his company @tideways. Their solution for PHP application performance monitoring is the best I have seen so far and you should definitely check it out if you have not done so already.

    It should come as no surprise that @tideways is committed to Open Source, @beberlei was the project lead for @doctrine2 after all. Their new tideways_xhprof extension, which started as a fork of Facebook's XHProf extension, provides a modern solution for profiling PHP applications.

    An interesting topic that came up in our discussion was DbUnit. Back in 2007, @mlively ported JUnit's DbUnit extension to PHP and PHPUnit. This extension for PHPUnit provides ready-to-be-used implementations of best practices for testing database interactions. It helps with fixture management and loading test data into the database as well as cleaning it up between tests. And the assertions it provides help with verifying the state of the database after INSERT, UPDATE, or DELETE operations.

    @beberlei shared that, from his experience, it is usually easier to implement a custom, project-specific solution for database fixture management than to use the generic solution provided by DbUnit. The effort to build such a custom solution is usually quite low, resulting in less than two hundred lines of code in a trait that is used by the database test case classes. He continued that when the application under test uses Doctrine then that aforementioned trait requires even less code thanks to functionality provided by the Connection object.

    At first, I was surprised that @beberlei does not use DbUnit. But then I realized that over the last couple of years I suggested the use of DbUnit less and less, for the most part because of the same reasons that @beberlei mentioned. In my experience, too, fixture management is usually much easier to maintain over time when it is implemented with the project's specifics in mind.

    @mlively stopped maintaining DbUnit years ago. After a while, @elazar took over the maintenance of DbUnit but he, too, is no longer active. In recent years, I made the changes required to keep DbUnit compatible with newer versions of PHPUnit. Occasionally I merge pull request to fix bugs. These pull requests, along with a bug report now and then, are the only signs I see that DbUnit is actually being used.

    A big concern that I have with DbUnit is the implementation of its assertions. For instance, the output they provide in case of a failure is frequently hard to read.

    (Somehow the above reads like it should have been a blog post.)

    Given that I neither use nor recommend the use of DbUnit, I am no longer motivated to perform even the minimal maintainenance work I have done these past few years. I will neither cut a release that will be compatible with next year's PHPUnit 8 nor will I clean up and refactor the codebase to leverage modern PHPUnit extension points.

    I will eventually archive this repository (no later than February 2019). Feel free to fork it in case you want to maintain DbUnit in the future.

    opened by sebastianbergmann 9
  • Return type of DefaultConnection::createQueryTable should match return type of Connection::createQueryTable

    Return type of DefaultConnection::createQueryTable should match return type of Connection::createQueryTable

    As the title suggests, Connection declares createQueryTable to return an ITable whereas DefaultConnect::createQueryTable has docs to return Table.

    This has tripped me up when I have strict typing enabled and the return type should have been an ITable, not a Table.

    opened by yalexyu 0
  • Feature request: Adjustable column widths in table diff output

    Feature request: Adjustable column widths in table diff output

    Current table diff output is set to 20 characters. All I want is a way to adjust this width.

    Specific use case:

    Pulling time stamps out of a PostgreSQL database puts them in the following format:

    TIMESTAMP WITH TIME ZONE(6)        2018-06-27 10:05:09.647832-05
    TIMESTAMP WITH TIME ZONE(0)        2018-01-01 00:00:00-06
    

    Many times I use assertDataSetsEqual to compare data with time stamps. Often, the engineer responsible for the code will not have taken into account the database's time zone, and as such the test data will be an hour off. In this case, the table diff will not generate useful output:

    Failed asserting that
    +---------------------------+
    | foo                       |
    +---------------------------+
    |            col            |
    +---------------------------+
    |  2018-06-27 16:58:23-09   |
    +---------------------------+
    
     is equal to expected (table diff enabled)
    +---------------------------+
    | foo                       |
    +---------------------------+
    |            col            |
    +---------------------------+
    | '2018-06-27 15:58:23' !=  |
    +---------------------------+
    

    If the columns were adjustable somehow it would be easier to get useful test output, but they're not adjustable.

    The "hack" I implemented locally is to pass in the column width via environment variable and just reference $_ENV inside AbstractTable - but I'm sure you could come up with something much better.

    opened by h3xx 1
  • [WIP] Handle edge-cases during ArrayDataSet construction

    [WIP] Handle edge-cases during ArrayDataSet construction

    For now I am just adding some tests that should address all of the edge-cases mentioned in #179

    Do these look right, or should some of these be handled differently?

    opened by nCrazed 1
  • Refactor __toString() from AbstractTable and ReplacementTable into a helper class

    Refactor __toString() from AbstractTable and ReplacementTable into a helper class

    There's a fair amount of common logic in these two methods and potential others in similar classes. Refactor it into a central helper class to make it more maintainable.

    refactoring 
    opened by elazar 0
  • Refactoring to leverage Comparator Framework

    Refactoring to leverage Comparator Framework

    PHPUnit 3.6 introduced a comparator framework that allows extensions to "overload" assertEquals() et. al. with custom comparison operations for objects. DbUnit should be refactored to leverage this by providing an implementation of PHPUnit_Framework_Comparator that can compare PHPUnit_Extensions_Database_DataSet objects and "just" provide convenience functionality to read data sets from CSV, XML, YAML, etc. as well as from a PDO connection.

    refactoring 
    opened by sebastianbergmann 0
Releases(1.4.0)
  • 1.4.0(Jun 5, 2015)

    • Support for PHPUnit 3.7.x has been removed, as BC-breaking changes were included in 4.x that prevent simultaneous support for both versions (@SenseException)
    • AbstractXmlDataSet has been modified to support handling large XML files (@davidmpaz)
    • AbstractXmlDataSet now returns more information for debugging when a parse error occurs (@davidmpaz)
    • .gitignore now includes the bin directory created when running composer install (@davidmpaz)
    • SymfonyYamlParser was modified to make its usage of the Symfony YAML component consistent with the requirements of v3.0 of that component (@DavidPrevot)
    Source code(tar.gz)
    Source code(zip)
Owner
Sebastian Bergmann
Sebastian Bergmann is the creator of PHPUnit. He co-founded thePHP.cc and helps PHP teams build better software.
Sebastian Bergmann
Provides generic data providers for use with phpunit/phpunit.

data-provider Installation Run composer require --dev ergebnis/data-provider Usage This package provides the following generic data providers: Ergebni

null 25 Jan 2, 2023
Qase-phpunit - Qase TMS PHPUnit reporter.

Qase TMS PHPUnit reporter Publish results simple and easy. How to integrate composer require qase/phpunit-reporter Example of usage The PHPUnit report

Qase TMS 6 Nov 24, 2022
Mockery - Designed as a drop in alternative to PHPUnit's phpunit-mock-objects library

Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its c

Mockery 10.3k Jan 1, 2023
:computer: Parallel testing for PHPUnit

ParaTest The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in y

null 2k Dec 31, 2022
PHP libraries that makes Selenium WebDriver + PHPUnit functional testing easy and robust

Steward: easy and robust testing with Selenium WebDriver + PHPUnit Steward is a set of libraries made to simplify writing and running robust functiona

LMC s.r.o. 219 Dec 17, 2022
Mock implementation of the Translation package, for testing with PHPUnit

PoP Translation - Mock Mock implementation of the Translation package, for testing with PHPUnit Install Via Composer composer require getpop/translati

PoP 1 Jan 13, 2022
The objective of ParaTest is to support parallel testing in PHPUnit

The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in your project and start using it with no additional bootstrap or configurations!

null 2k Dec 31, 2022
Learn unit testing with PHPUnit.

PHPUnit Exercise Running PHPUnit ./vendor/bin/phpunit # with filter which tests to run ./vendor/bin/phpunit --filter <pattern> Running Pint ./vendor/

Nopal 2 Aug 23, 2022
SimpleTest is a framework for unit testing, web site testing and mock objects for PHP

SimpleTest SimpleTest is a framework for unit testing, web site testing and mock objects for PHP. Installation Downloads All downloads are stored on G

SimpleTest 147 Jun 20, 2022
The most powerful and flexible mocking framework for PHPUnit / Codeception.

AspectMock AspectMock is not an ordinary PHP mocking framework. With the power of Aspect Oriented programming and the awesome Go-AOP library, AspectMo

Codeception Testing Framework 777 Dec 12, 2022
vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

vfsStream vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with

null 1.4k Dec 23, 2022
Rector upgrades rules for PHPUnit

Rector Rules for PHPUnit See available PHPUnit rules Install composer require rector/rector-phpunit Use Sets To add a set to your config, use Rector\P

RectorPHP 34 Dec 27, 2022
Add mocking capabilities to Pest or PHPUnit

This repository contains the Pest Plugin Mock. The Mocking API can be used in regular PHPUnit projects. For that, you just have to run the following c

PEST 16 Dec 3, 2022
A sample RESTful API in Laravel with PHPunit test.

Laravel PHP Framework URL | URI | Action |

Fasil 9 Jul 11, 2020
PHPUnit Application Architecture Test

PHPUnit Application Architecture Test Idea: write architecture tests as well as feature and unit tests Installation Install via composer composer requ

null 19 Dec 11, 2022
PHPUnit to Pest Converter

PestConverter PestConverter is a PHP library for converting PHPUnit tests to Pest tests. Before use Before using this converter, make sure your files

null 10 Nov 21, 2022
Allows the running of PHPUnit within ExpressionEngine

EE Unit Tests EE Unit Tests is an Add-on for ExpressionEngine that allows developers to execute unit tests from the Command Line. EE Unit Tests uses P

Eric Lamb 6 Jan 14, 2022
Magento PHPUnit Integration

Magento PHPUnit Integration Magento is a quite complex platform without built in unit test suite, so the code is not oriented on running tests over it

EcomDev B.V. 303 Dec 18, 2022
Report high memory usage PHPUnit tests: Managed by opg-org-infra & Terraform

phpunit-memory-usage Report high memory usage PHPUnit tests: Managed by opg-org-infra & Terraform Configuration Add into the phpunit.xml extensions se

Ministry of Justice 2 Aug 4, 2022