简体   繁体   English

使用 phpunit 进行 Laravel 测试

[英]Laravel testing with phpunit

How can I make sure that when I'm testing in Laravel with phpunit and for example I want to test my api route /test/1 it uses my test database?如何确保当我使用 phpunit 在 Laravel 中进行测试时,例如我想测试我的 api 路由/test/1它使用我的测试数据库?

I already made a test connection and changed my phpunit.xml file.我已经建立了一个测试连接并更改了我的 phpunit.xml 文件。 I changed DB_CONNECTION to the test connection that I made.我将DB_CONNECTION更改为我DB_CONNECTION的测试连接。

<env name="DB_CONNECTION" value="mysql_testing"/>

But it when I make a post request I receive data from the development database?但是当我发出 post 请求时,我会从开发数据库接收数据吗?

In your Config/database.php file, what is the value of database in mysql_testing ?在您的Config/database.php文件中, mysql_testing中 database 的值是mysql_testing It should be like this:应该是这样的:

'mysql_testing' => [ 
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('TEST_DB_DATABASE', 'db_testing'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

And database db_testing must exists.并且数据库db_testing必须存在。

Inside one of your test files, add the following to output your current DB_CONNECTION :在您的测试文件之一中,添加以下内容以输出您当前的DB_CONNECTION

dd(env('DB_CONNECTION'));

You should get mysql_testing in your test output if PHPUnit.xml is properly setup.如果 PHPUnit.xml 设置正确,您应该在测试输出中获得mysql_testing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM