简体   繁体   中英

Unit-testing with CakePhP and PHPUnit

I`m trying to do unit-testing with CakePhP 2.3 and PHPUnit 2.7. I want to test the index function in my customer's controller. In my controller I have:

public function index() {

    $this->Customer->recursive = -1;
    $data = $this->paginate('Customer', array( 'Customer.status'=>'active'));
    $this->set('customers', $data);

}

I tried to follow the examples in book.cakephp.org, so I created Fixture class in which I`m importing the Customer schema and all the records.

class CustomerFixture  extends CakeTestFixture{

  public $import = array('model' => 'Customer', 'records' => true);

}

And finally my test class looks like this:

class CustomersControllerTest extends ControllerTestCase {

  public $fixtures = array('app.customer');

   public function testIndex() {

      $result = $this->testAction('/customers/index');
      debug($result);
   }
}

When I run my test I have the following error:

Database Error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '8' for key 'PRIMARY'

Do you have any ideas what can be the problem?

In your database.php in app/Config folder you have to add a $test variable.

For example

class DATABASE_CONFIG {

    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => true,
        'host' => 'localhost',
        'port' => 3306,
        'login' => 'root',
        'password' => 'xxxx',
        'database' => 'mydatabase',
        'encoding' => 'utf8'
    );

    public $test = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'port' => 3306,
        'login' => 'root',
        'password' => 'xxxx',
        'database' => 'mydatabase_test',
        'encoding' => 'utf8'
    );

}

Then your unit testing will use the mydatabase_test for testing your code. Because now it uses the default database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM