How to check if the class was instantiated through the DataProvider using PHP Unit

0

Could anyone make an example? Considering my class below:

class MinhaClasse
{

    private $param;

    public function __construct($params = []) {

      return null;

    }

} 

I have my test class:

require_once "MinhaClasse.php";

class MinhaClasseTest extends PHPUnit_Framework_TestCase
{

    /**
     * @dataProvider additionProvider
     */

    public function additionProvider()
    {
        return array(
          array('?????', null, null),
          array(0, 1, 1),
          array(1, 0, 1),
          array(1, 1, 3)
        );
    }

    public function testShouldMyClassIsInstantiate($instance, $value, $expected)
    {
        $this->assertEquals($expected, $value);
    }   
}
    
asked by anonymous 02.09.2015 / 15:08

2 answers

0

I came up with the solution by myself, to test an instance just do the following, as described in the documentation: link

require_once "MinhaClasse.php";

class MinhaClasseTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function additionProvider()
    {
        return array(
          array('MinhaClasse', new MinhaClasse()),
        );
    }

    public function testShouldMyClassIsInstantiate($expected, $instance)
    {
      $this->assertInstanceOf($expected, $instance,'The Class "{$expected}" can\'t be instantiated'); 
    }   
}
    
08.09.2015 / 15:15
1

A DataProvider method returns an array of arrays or an object that implements the Iterator interface. The test method will be invoked with the contents of the array and its arguments.

Some key points using DataProvider:

  • DataProvider method must be public.
  • DataProvider will return a array of data.
  • Use the test annotation (@dataProvider) to declare your dataProvider method.

It's really very simple to use dataProvider. First let's create a new public method, which returns a dataset array as arguments to the test method. Then we add a note to the test method to say that PHPUnit will provide the arguments.

  <?php
require 'Calculator.php';

class CalculatorTests extends PHPUnit_Framework_TestCase
{
    private $calculator;

    protected function setUp()
    {
        $this->calculator = new Calculator();
    }

    protected function tearDown()
    {
        $this->calculator = NULL;
    }

    public function addDataProvider() {
        return array(
            array(1,2,3),
            array(0,0,0),
            array(-1,-1,-2),
        );
    }

    /**
     * @dataProvider addDataProvider
     */
    public function testAdd($a, $b, $expected)
    {
        $result = $this->calculator->add($a, $b);
        $this->assertEquals($expected, $result);
    }

 }

Font

Manual

    
02.09.2015 / 16:06