jeudi 3 septembre 2015

why is my mysqli instance failing when unit testing?

I'm afraid I'm rather new to unit testing.

I have a PHP class called "dbRecord" that I use to abstract database tables/records and am trying to apply unit testing to it. When I do so though, the mysqli object that it uses seems to break.

As an example, I have a user class (an extension of the abstract dbRecord class) that works quite nicely if I create and save a user in a shell. That would be something like this:

$u = new userClass();
$u->setEmail('foo@bar.com');
$u->save();

That works very nicely if I use it in a web site or from a php shell. It creates an object, sets the e-mail value, and then saves it in the database, assigning the auto-incrementing id field back to the $u object.

If I try to create a unit test though, it fails upon saving the record. The error is happening when it tries to use mysqli::real_escape_string, but it happens with any other member of the mysqli object (I have tested that just in case). The error I get is:

mysqli::real_escape_string(): Couldn't fetch mysqli

So I assume there's something I'm failing to understand in the scope of things when doing the unit test. Here's the full code of the test I'm running:

<?php
require_once "../dbTemplate.php";
class TestOfUserClass extends PHPUnit_Framework_TestCase {
        function testAssignUserValues(){
                $usr = new userClass();
                $usr->setEmail('foo@bar.com');
                $this->assertTrue($usr->getEmail() == 'foo@bar.com');
                $usr->save();
        }
}

The code that's actually throwing that exception is in the save call. Here's what it looks like:

    public function save(){
            if($this->_isNewRecord){
                    // we're creating a new record
                    $query = "INSERT INTO `" . $this->_mysqli->real_escape_string($this->_tableName) . "`";
                    ...

At this point I'm rather lost as to why it's not able to use that mysqli instance. Again, this works perfectly under regular usage (either through apache on a web page or through a php shell). It's only when using the test cases that it dies. I tried it with both Simpletest and PHPUnit, with the same results.

The structure of how that mysqli object is accessed goes like this:

In my test file (test1.php), "../dbTemplate.php" is included at the top.

In dbTemplate.php:

  • the mysqli object is created at the top, assigned to a variable called $mysqli.
  • the dbRecord abstract class is then defined
  • in that definition's construct, $this->_mysqli is assigned the value of $mysqli.

The test file is exactly as quoted above.

Then of course, I run "phpunit test1.php"

Does anyone see what I'm doing wrong here?

Aucun commentaire:

Enregistrer un commentaire