5

I am testing a model in CakePHP 2 and have mocked a model like this:

$this->User = $this->getMock('User', array(
  '_saveUploadedFile',
  '_removeUploadedFile',
)); 
$this->User->expects($this->any())
        ->method('_saveUploadedFile')
        ->with($data, Configure::read('App.myDirectory'), true);
        ->will($this->returnValue(true));
$this->User->expects($this->any())
        ->method('_removeUploadedFile')
        ->with($data, Configure::read('App.myDirectory'))
        ->will($this->returnValue(true));

Since any operation with the database raises the following error:

"Database table mock__user_b6241a4cs for model User was not found."

I redefined the model information:

$this->User->alias = 'User';
$this->User->useTable = 'users';

Now the test works well, but it's using the $default database in database.php instead of $test. What can be happening?

Why the database configuration for testing changes when using mocked objects? Could it be related to database permissions that causes the mocked object not being able to create its custom tables?

Thanks!

2 Answers 2

2

I finally solved the problem by passing the correct parameters to the model constructor in getMock() third agument:

$this->User = $this->getMock('User',
  array('_saveUploadedFile', '_removeUploadedFile'),
  array(false, 'users', 'test')
);

Applying what is said in Stubs section of PHPUnit documentation, this third argument indicates that I want to use the users table and the test datasource.

I have to keep the redefinition of the alias property though:

$this->User->alias = 'User';

because a simple $this->User->read(null, 1) raises an error saying that 'User.a_column' couldn't be found.

Thanks to José Lorenzo.

Sign up to request clarification or add additional context in comments.

Comments

0

I haven't encountered this specific problem before, but I'm curious if you've tried setting the specific connection you want. So the same way you set alias and useTable:

$this->User->useDbConfig = 'test';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.