最后,我已经开始上课了,以防万一。
主要问题是 DomCrawler 需要一个绝对 URI,但是如果您将该 URI 传递给 CakePHP,它将无法很好地工作,所以这是我的课程
<?php
namespace App\Test\TestCase\Controller;
use Cake\TestSuite\IntegrationTestCase;
use Symfony\Component\DomCrawler\Crawler;
class BaseIntegrationTestCase extends IntegrationTestCase
{
public function get( $url )
{
$result = parent::get($url);
$url = (stripos($url, 'http://') !== false) ? $url : 'http://localhost' . $url ;
$crawler = new Crawler( null, $url );
$crawler->addContent($this->_response);
return $crawler;
}
public function post($url, $data = [])
{
$parsed = parse_url($url);
$result = parent::post($parsed['path'], $data);
$url = (stripos($url, 'http://') !== false) ? $url : 'http://localhost' . $url ;
$crawler = new Crawler( null, $url );
$crawler->addContent($this->_response);
return $crawler;
}
public function submit( \Symfony\Component\DomCrawler\Form $form )
{
return $this->post( $form->getUri(), $form->getPhpValues() );
}
}
使用示例:
<?php
use App\Test\TestCase\Controller\BaseIntegrationTestCase;
class AdminsControllerTest extends BaseIntegrationTestCase
{
function testSomething()
{
$data = ['hours' => array (
[
'day' => 'Lunes',
'from' =>'10',
'to' => '22'
],
[
'day' => 'Martes',
'from' =>'10',
'to' => '22'
],
[
'day' => 'Miercoles',
'from' =>'10',
'to' => '22'
],
[
'day' => 'Jueves',
'from' =>'10',
'to' => '22'
],
[
'day' => 'Viernes',
'from' =>'10',
'to' => '23'
],
)
];
$crawler = $this->get('/miweb/add-page/TimeTable/2');
$this->assertResponseOk();
$this->assertResponseContains( 'horario' );
$form = $crawler->selectButton('Guardar')->form();
$form->setValues( $data );
$crawler = $this->submit($form);
// $this->post('/miweb/add-page/TimeTable/2', $data);
$this->assertResponseContains( 'Jueves' );
$this->assertResponseContains( 'Viernes' );
$this->assertResponseContains( '23' );
$this->assertCount( 7, $crawler->filter('.row.time') );
$post = TableRegistry::get('Posts')->get(3, ['contain' => ['Elements', 'Parent']]);
$this->assertContains( 'de 10 a 22', $post->content );
$this->assertContains( 'Martes', $post->content );
$this->assertEquals( 'Horarios', $post->title );
$this->assertEquals( '1', $post->site_id );
$this->assertEquals( 'horarios', $post->slug );
$this->assertEquals( 'TimeTable', $post->class );
$this->assertRedirect('/miweb/edit-page/3');
}
}