# 测试
`phpunit.xml `是phpunit的配置文件。默认情况下,该文件只在 `/tests/Feature` 和 `/tests/Unit` 中运行测试。
为了测试你的模块,需要将它们的路径添加到这个文件中,手动为每个模块添加条目是不可取的,所以使用通配符 * 动态地包含这些模块:
```php
./Modules/*/Tests/Feature
./Modules/*/Tests/Unit
```
还要确保你已经将数据库连接设置为 sqlite 并使用内存数据库:
```php
```
## phpunit.xml 示例
文件看起来像这样
```php
./tests/Unit
./tests/Feature
./Modules/*/Tests/Feature
./Modules/*/Tests/Unit
./app
```
现在,当 phpunit 从模块运行测试时,全局的tests文件夹将运行。
## 运行测试
当你运行phpunit时:
```php
vendor/bin/phpunit
```
所有测试都将运行。
## 运行单个测试
如果你只想运行一个测试方法、类或模块,可以使用filter标志:
```php
vendor/bin/phpunit --filter 'contacts'
```
这将运行 Contacts 模块中的所有测试。
运行一个测试方法:
```php
vendor/bin/phpunit --filter 'can_delete_contact'
```
这将匹配测试
```php
/** @test */
public function can_delete_contact(): void
{
$this->authenticate();
$contact = Contact::factory()->create();
$this->delete(route('app.contacts.delete', $contact->id))->assertRedirect(route('app.contacts.index'));
$this->assertDatabaseCount('contacts', 0);
}
```
测试一个完整的测试文件:
```php
vendor/bin/phpunit --filter 'ContactTest'
```
## 使用 PestPHP
使用 PestPHP [https://pestphp.com](https://pestphp.com)。
你经常需要运行 Pest `testCase` 类,并在文件开头导入它。
```php
uses(Tests\TestCase::class);
```
当使用 Pest 时,你不需要类,以下是一个有效的文件:
```php
authenticate();
$this->get(route('app.contacts.index'))->assertOk();
});
test('can delete contact', function() {
$this->authenticate();
$contact = Contact::factory()->create();
$this->delete(route('app.contacts.delete', $contact->id))->assertRedirect(route('app.contacts.index'));
$this->assertDatabaseCount('contacts', 0);
});
```
运行测试套件:
```php
vendor/bin/pest
```
如果你只想运行一个测试方法、类或模块,可以使用filter标志:
```php
vendor/bin/pest --filter 'contacts'
```
这将匹配测试
```php
test('can_delete_contact', function() {
$this->authenticate();
$contact = Contact::factory()->create();
$this->delete(route('app.contacts.delete', $contact->id))->assertRedirect(route('app.contacts.index'));
$this->assertDatabaseCount('contacts', 0);
});
```