S
S
solncebro2019-01-29 04:20:04
PHPUnit
solncebro, 2019-01-29 04:20:04

How can PHPunit emulate a database query?

Hello!
I want to write a test for a function:

function calculateLimits($pdo, $interval, $timeStart)
{
    $intervalMinutes = getMinutesFromInterval($interval);

    $lastUpdate = $pdo->query("SELECT updated FROM last_updates
                                    WHERE table_name = 'candles${interval}';")->fetchColumn();
    $lastUpdateCarbon = Carbon::parse($lastUpdate, 'UTC');
    $diffInSecond = $timeStart->diffInSeconds($lastUpdateCarbon);

    $limit = $diffInSecond / (60 * $intervalMinutes);
    
    return ceil($limit);
}

As you can see, there is a variable there that depends on the response from the DB. I can't figure out how to emulate a database query. I do it like this:
class CandlestickTest extends TestCase
{
    private $stub;

    public function setUp()
    {
        $this->stub = $this->getMockBuilder('PDO')
                            ->disableOriginalConstructor()
                            ->setMethods(['query', 'fetchColumn'])->getMock();
    }

    public function testCalculateLimits()
    {
        $this->stub->method('query')->with("SELECT updated FROM last_updates
                                    WHERE table_name = 'candles30m';")
                    ->method('fetchColumn')->willReturn('2019-01-26 23:50:49');
        $this->assertEquals(48, C\calculateLimits($this->stub, '30m', '2019-01-27 23:50:49'));
    }
}

As soon as ->method('fetchColumn') after method('query')->with(), the tests give me a warning:
Method name matcher is already defined, cannot redefine
Google does not return anything for this error - only similar errors. Why does it think that I am overriding the method?! I don't understand how to make it work.
I just need to just during testing the calculateLimits function, when a request to the database occurs, this very request is not executed and the string '2019-01-27 23:50:49' is simply substituted, and not that's all.
PS. I do not understand the purpose of with and will. It seems that PHPunit wants me to substitute the REAL arguments in with and the actual return of the query function in will.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question