Created
March 11, 2013 04:32
-
-
Save eddieajau/5131895 to your computer and use it in GitHub Desktop.
A strategy for mocking a PSR-3 logger. This assume the class being tested has a `log` method which probably checks if the logger has been set and then proxies to `$this->logger->log`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Psr\Log; | |
class TheTest extends \PHPUnit_Framework_TestCase | |
{ | |
/** | |
* The class we are testing. | |
*/ | |
protected $instance; | |
/** | |
* Track the logger calls. | |
*/ | |
protected $logs; | |
/** | |
* Mocks the log method to track if logging is working. | |
* | |
* @param Log\LogLevel $level The level. | |
* @param string $message The message. | |
* @param array $context The context. | |
* | |
* @return void | |
*/ | |
public function mockLog($level, $message, $context) | |
{ | |
$this->logs[] = array( | |
'level' => $level, | |
'message' => $message, | |
'context' => $context, | |
); | |
} | |
/** | |
* Tests the log method. | |
* | |
* @return void | |
*/ | |
public function testLog() | |
{ | |
$this->logs = array(); | |
$mockLogger = $this->getMock('Psr\Log\AbstractLogger', array('log'), array(), '', false); | |
$mockLogger->expects($this->any()) | |
->method('log') | |
->will($this->returnCallback(array($this, 'mockLog'))); | |
$this->instance->log(Log\LogLevel::DEBUG, 'Debug', array('sql' => true)); | |
$this->assertEmpty($this->logs, 'Logger not set up yet.'); | |
// Set the logger and try again. | |
$this->instance->setLogger($mockLogger); | |
$this->instance->log(Log\LogLevel::DEBUG, 'Debug', array('sql' => true)); | |
$this->assertEquals(Log\LogLevel::DEBUG, $this->logs[0]['level']); | |
$this->assertEquals('Debug', $this->logs[0]['message']); | |
$this->assertEquals(array('sql' => true), $this->logs[0]['context']); | |
} | |
/** | |
* Sets up the fixture. | |
* | |
* This method is called before a test is executed. | |
* | |
* @return void | |
*/ | |
protected function setUp() | |
{ | |
$this->instance = new TheClass; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment