Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Testing a select in a method with dataset

I try to test a method that makes a SELECT query and return the rows found. I would like to check that this method doesn't return something else, given a dataset. I found so many docs about creating the dataset but nothing about using it in my case... Thanks for your help.

The method to test is:

class A
{
  public static function myMethod()
  {
    $result = mysql_query("SELECT * FROM user");
    [...]
    return $rows;
  }
}

The test class is:

class ATest extends PHPUnit_Extensions_Database_TestCase
{
  protected $pdo;

  public function __construct()
  {
    $this->pdo = new PDO('mysql:host=localhost;dbname=db_name',
                         'login', 'password');
  }

  public function getConnection()
  {
    return $this->createDefaultDBConnection($this->pdo, 'db_name');
  }

  public function getDataSet()
  {
    return $this->createFlatXMLDataSet('mydataset.xml');
  }

  public function testMyMethod()
  {
    $actual = A::myMethod();
    $this->assertEquals(array([...]), $actual);
    // For this test, I get a mySQL error "No database selected"
    // in A::myMethod()!
  }
}

Here is the content of mydataset.xml:

<?xml version="1.0" ?>
<dataset>
  <user iduser="1" name="John" />
  <user iduser="2" name="James" />
</dataset>
like image 772
Johor Avatar asked Nov 19 '25 23:11

Johor


1 Answers

what I did in my case was I made the connection to the database using pdo like so:

static private $pdo=null;
private $conn=null;
    public function getConnection()
        {
            if($this->conn===null)
            {
                if(self::$pdo===null)
                {
                    self::$pdo = new PDO("mysql:host=yourhost;dbname=yourdbname_",
                "yourusername", "yourpassword");
                }
                $this->conn= $this->createDefaultDBConnection(self::$pdo, 'yourdbname_');
                return $this->conn;
            }
        }, 

then as for the test, this block below gets all the values in the testdb and compares it with the xml file.

 public function testGetAll()
            {
                $resultingTable = $this->db
                ->createQueryTable("yourtable",
                "SELECT * FROM yourtable");
                 $expectedTable = $this->getDataSet()
                ->getTable("yourtable");
            $this->assertTablesEqual($expectedTable,
                $resultingTable);   
            }

That worked fine for me and should allow you get all the values from the testdb and assert that they are the same with the xml values.

like image 160
Ego_I Avatar answered Nov 22 '25 13:11

Ego_I



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!