假设您的示例描述了一个SessionHandler
类,它看起来类似于:
class SessionHandler
{
public function __construct($sessionTableName, $sessionName, \PDO $databaseConnection)
{
$this->DBTableName = $sessionTableName;
$this->sessionName = $sessionName;
$this->databaseConnection = $databaseConnection;
}
// among others, your method write($sessionId, $sessionData) follows
}
这可以涵盖方法write()
:
public function testWriteInsertsOrUpdatesSessionData()
{
/**
* initialize a few explaining variables which we can refer to
* later when arranging test doubles and eventually act
*/
$sessionTableName = 'sessions';
$sessionName = 'foobarbaz';
$sessionId = 'foo';
$sessionData = serialize([
'bar' => 'baz',
]);
$executed = true;
/**
* create a test double for the statement that we expect to be returned
* from `PDO::prepare()`
*/
$statement = $this->createMock(\PDOStatement::class);
/**
* set up expectations towards which methods should be invoked
* on the statement, specifying their order
*/
$statement
->expects($this->at(0))
->method('bindValue')
->with(
$this->identicalTo(':session_id'),
$this->identicalTo(sessionId)
);
$statement
->expects($this->at(1))
->method('bindValue')
->with(
$this->identicalTo(':session_name'),
$this->identicalTo($sessionName)
);
$statement
->expects($this->at(2))
->method('bindValue')
->with(
$this->identicalTo(':session_data'),
$this->identicalTo(sessionData)
);
$statement
->expects($this->at(3))
->method('execute')
->willReturn($executed);
/**
* create a test double for the database connection we inject
* into SessionHandler during construction
*/
$databaseConnection = $this->createMock(\PDO::class);
$databaseConnection
->expects($this->once())
->method('prepare')
->with($this->identicalTo(sprintf(
'INSERT INTO `%s` (`session_id`,`session_name`,`session_data`) VALUES(:session_id, :session_name, :session_data) ON DUPLICATE KEY UPDATE `session_data`=:session_data;',
$sessionTableName
)))
->willReturn($statement);
$sessionHandler = new SessionHandler(
$sessionTableName,
$sessionName,
$databaseConnection
);
$result = $sessionHandler->write(
$sessionId,
$sessionData
);
$this->assertSame($executed, $result);
}
供参考,请参阅: