ZF2 / PHPUnit: Mock Zend / Db / Adapter / Adapter for future use

Target: Unit test InputFilter in Zend Framework 2.

Problem: DockAdapter required.

Since I'm relatively new to Unit Testing, I just started mocking classes. After many studies, I still can’t find a suitable solution for my problem, so here we go to the filter to get started:

class ExampleFilter extends Inputfilter { protected $dbAdapter; public function __construct(AdapterInterface $dbAdapter) { $this->dbAdapter = $dbAdapter; } public function init() { $this->add( [ 'name' => 'example_field', 'required' => true, 'filters' => [ ['name' => 'StringTrim'], ['name' => 'StripTags'], ], 'validators' => [ [ 'name' => 'Db\NoRecordExists', 'options' => [ 'adapter' => $this->dbAdapter, 'table' => 'example_table', 'field' => 'example_field', ], ], ], ] ); } } 

Without an adapter, testing this filter will be quite simple. My problem is creating a filter in my TestClass, as shown here:

 class ExampleFilterTest extends \PHPUnit_Framework_TestCase { protected $exampleFilter; protected $mockDbAdapter; public function setUp() { $this->mockDbAdapter = $this->getMockBuilder('Zend\Db\Adapter') ->disableOriginalConstructor() ->getMock(); $this->exampleFilter = new ExampleFilter($this->mockDbAdapter); } 

}

When creating a filter like this, the ExampleFilter class will end up giving the wrong class to its constructor. It gets the layout of the object, waiting for one of the types Zend \ Db \ Adapter \ Adapter.

I could create a real adapter, of course, but I want to avoid making real database queries, as this is a Unit test, and it will be far beyond my module for testing.

Can someone tell me how I can achieve my goal of testing a filter with a mocked DbAdapter?

+1
source share
1 answer

Well ... As I commented on the gontrollez hint, I already felt my mistake. I needed to create a layout of "Zend / Db / Adapter / AdapterInterface" instead of "/ Zend / Db / Adapter".

Thanks for taking me on the right track anyway gontrollez :)

+1
source

Source: https://habr.com/ru/post/1014835/


All Articles