仍在学习如何测试php
我现在有了一个工作界面(我想)——其中一个功能是创建一系列记录,我现在想测试它。我承认我对测试知之甚少,所以问题多于知识。
所以
我的界面目前看起来是这样的:
interface TicketCreatorInterface {
public function createTicket($input, $book);
}
我的"存储库"类如下:
Class TicketCreator implements TicketCreatorInterface {
protected $ticket;
public function __construct(TicketAudit $ticketAudit)
{
$this->ticket = $ticketAudit;
}
public function createTicket($input, $book) {
$counter = $input['start'];
while($counter <= $input['end']) {
$this->$ticket->create(array(
'ticketnumber'=>$counter,
'status'=>'unused',
'active'=>1
));
$this->ticket->book()->associate($book);
$counter = $counter+1;
}
return $counter;
}
我的测试尝试是这样的:
public function testCreateCreatesTickets(TicketCreatorInterface $ticketCreator) {
//arrange
$book = Mockery::mock('Book');
//act
$response = $ticketCreator->createTicket(array('start'=>1000, 'end'=>1001), $book);
// Assert...
$this->assertEquals(true, $response);
}
我第一次尝试不提示接口类型,因为没有提示,我得到了一个没有对象的错误。我试着在接口上创建一个实例,但你做不到,所以在函数中使用了类型提示
当我运行测试时,我得到的错误是:
Argument 1 passed to TicketCreatorTest::testCreateCreatesTickets() must implement interface TicketCreatorInterface, none given
创建接口对我来说是一种新方法,所以还不完全了解
那么,我该如何测试这个函数是否按预期创建了一个票证呢?
我已经在内存数据库中使用sqlite测试了模型
您需要在测试中创建TicketCreator的实例来调用方法。将测试更改为:
public function testCreateCreatesTickets() {
//arrange
$book = Mockery::mock('Book');
$ticketAudit = Mockery::mock('TicketAudit');
$ticketCreator = new TicketCreator($ticketAudit);
//act
$response = $ticketCreator->createTicket(array('start'=>1000, 'end'=>1001), $book);
// Assert...
$this->assertEquals(true, $response);
}
由于在构造函数中需要TicketAudit,因此还需要创建该对象的mock并将其传递给构造函数。
PHPUnit向测试用例提供参数的唯一时间是当您有一个数据提供程序或测试依赖于另一个测试时。
http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers
http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.examples.StackTest2.php
请记住,您不会创建接口的实例。如果我想确保您的对象实现一个接口,我将创建一个测试,使用assertInstanceOf
检查该对象是否是接口的实例。