2

I started today to use PHPUnit Tests on PhpStorm. I could test almost all functions, except the functions which requires database connection.

Function:

public function getProductID()
{
     $this->product_id = $this->db->GetOne("select product_id from table1 where id = {$this->id}");
     return $this->product_id['product_id'];
}

On my test case, I got error:

PHP Fatal error: Call to a member function GetOne() on null

I have defined:

global $_db;
$this->db = $_db;
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
62009030
  • 347
  • 1
  • 5
  • 20

1 Answers1

5

You should mock/stub your connection in your test, something like

$stub = $this
    ->getMockBuilder('YourDBClass') // change that value with your REAL db class
    ->getMock();

// Configure the stub.
$stub
    ->method('GetOne')
    ->willReturn(); // insert here what you expect to obtain from that call

That way you're test is isolated from other dependencies.

If you want to do a different kind of test (that use REAL DB data, for example) you should not do unit testing but functional testing or integration testing

Explanation

Here what you're testing is getProductID() (a method) that should return basically an integer. Period. This is (or should be) the purpose of your test. So you want only to check if an integer is returned, not THAT integer is returned. If you stop to think about this, you probably notice that you want to be not influenced by any other dependency result.

Community
  • 1
  • 1
DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • hi @DonCallisto, I need to do use real DB data. it is not possible on unitTest? Sorry for noob question, but i just started use it today – 62009030 Feb 24 '16 at 12:03
  • @62009030 it's not recommended. moreover, if your db isn't passed directly to your SUT (system under test) but, for example, is injected via dependency injection, it's also virtually impossible to use a real db connection. – DonCallisto Feb 24 '16 at 12:05
  • There's some way to inject the connection to db ? Thanks for your explanation – 62009030 Feb 24 '16 at 12:07
  • Thanks for explanation! I'm trying use the stub, but without success yet. YouDBClass shoud be my $ths-DB and method GetOne or name of function? WillReturn is where I expect to receive in this case a int , am I thinking right? – 62009030 Feb 24 '16 at 12:18
  • @62009030 no, you should create the stub with equivalent of you expect for class where you using the method you are testing. WillReturn in your case should return what GetOne returns (an array?). After that, to use The stub, you should pass in class constructor direcrly or via independency injection. I suggest to read phpunit manual :) – DonCallisto Feb 24 '16 at 12:32