Symfony学习笔记 - Symfony Documentation - The Basics(2)

3、Tests

Symfony集成了PHPUnit作为测试框架。可以包含unit test、integration test和application test。

  1. 按照惯例,test目录下,应该复制一份与你应用目录相同的目录。
  2. 为了避免环境污染,每次的测试可以通过bootKernel()的方式,reboot kernel。
  3. 可以通过getContainer()来获取到ServiceContainer。
  4. DAMADoctrineTestBundle可以每次交互时,用的是未被修改的database
  5. application test一般在Controller目录下,作为request/response的处理
  6. 可以模拟客户端,$crawler = $client->request('GET', '/post/hello-world');,来进行测试
  7. Client可以可以执行其他的操作,比如:
    $crawler = $client->followRedirect(); $client->followRedirects(); $client->followRedirects(false); $client->loginUser($testUser, 'my_firewall') //登录 $client->xmlHttpRequest('POST', '/submit', ['name' => 'Fabien']); //ajax请求 $client->catchExceptions(false); //异常处理 $client->request('GET', '/post/hello-world'); $client->clickLink('Click here'); //模拟点击链接 $client->request('GET', '/post/hello-world'); $crawler = $client->submitForm('Add comment', [ 'comment_form[content]' => '...', ]); //模拟提交Form ...
  8. 测试Response,验证输出符合预期。包括一系列的Assertion函数,比如:
    assertResponseIsSuccessful(string $message = '', bool $verbose = true) Asserts that the response was successful (HTTP status is 2xx). assertResponseStatusCodeSame(int $expectedCode, string $message = '', bool $verbose = true) Asserts a specific HTTP status code.
  9. 测试Request,验证输入符合预期。包括一系列的Assertion函数,比如
    assertRequestAttributeValueSame(string $name, string $expectedValue, string $message = '') Asserts the given request attribute is set to the expected value.
  10. 验证Browser,符合预期:
    assertBrowserHasCookie(string $name, string $path = '/', ?string $domain = null, string $message = '')/assertBrowserNotHasCookie(string $name, string $path = '/', ?string $domain = null, string $message = '')
  11. Crawler Assertions
    assertSelectorExists(string $selector, string $message = '')/assertSelectorNotExists(string $selector, string $message = '') Asserts that the given selector does (not) match at least one element in the response.
  12. Mailer Assertions
    assertEmailCount(int $count, ?string $transport = null, string $message = '') Asserts that the expected number of emails was sent.
  13. Notifier Assertions
    assertNotificationCount(int $count, ?string $transportName = null, string $message = '') Asserts that the given number of notifications has been created (in total or for the given transport).
posted @ 2025-09-09 12:20  繁星灼灼  阅读(6)  评论(0)    收藏  举报