如何避免 phpunit 测试输出被截断:
1) Tests\ApiTest::testGetMetricList
GuzzleHttp\Exception\ServerException: Server error: `GET http://localhost/micobe/myproject_p4/index.php/investors/get_metric_list` resulted in a `500 Internal Server Error` response:
<br />
<font size='1'><table class='xdebug-error xe-exception' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr (truncated...)
/var/www/html/landing-myproject-page/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
/var/www/html/landing-myproject-page/vendor/guzzlehttp/guzzle/src/Middleware.php:65
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:203
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:156
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/TaskQueue.php:47
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:246
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:223
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:267
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:225
/var/www/html/landing-myproject-page/vendor/guzzlehttp/promises/src/Promise.php:62
/var/www/html/landing-myproject-page/vendor/guzzlehttp/guzzle/src/Client.php:131
/var/www/html/landing-myproject-page/app/Http/Controllers/ApiController.php:171
/var/www/html/landing-myproject-page/tests/ApiTest.php:31
Run Code Online (Sandbox Code Playgroud) 我有 Laravel 5.5,我决定将路径分组到文件中,以便以更有意义的方式组织它们。
这是一个简化的示例 - Web 路由文件位于:
app/Http/Routes/Web/static.php
app/Http/Routes/Web/test.php
Run Code Online (Sandbox Code Playgroud)
static.php包含:
<?php
declare(strict_types=1);
namespace Foo\Http\Routes\Web;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Run Code Online (Sandbox Code Playgroud)
test.php包含:
<?php
declare(strict_types=1);
namespace Foo\Http\Routes\Web;
use Illuminate\Support\Facades\Route;
Route::get('/test', function () {
return 'test'; // just to simplify
});
Run Code Online (Sandbox Code Playgroud)
RouteServiceProvider.php包含:
<?php
declare(strict_types=1);
namespace Foo\App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
protected $namespace = 'Foo\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public …Run Code Online (Sandbox Code Playgroud) 我创建了一个服务,其中从外部源检索 JSON 并进行查询。我希望能够独立于该服务来测试使用该服务的功能。如何在 PHP 单元测试中模拟 JSON 文件以测试这些函数?JSON 文件格式如下:
{
"data": [
{
"title": "Development",
"children": [
{
"title": "Settings",
"channel_types": [
{
"title": "Network"
}
]
},
{
"title": "Testing",
"channel_types": [
{
"title": "Social"
}
]
}
],
"created_at": 1523464038,
"updated_at": 1523464038,
"id": "5ace37664e1d4400a04ffaf2"
}
]
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个 PHPUnit 测试,在允许用户发出发布请求之前首先对用户进行身份验证,但出现错误
1)Tests\Feature\BooksTest::test_onlyAuthenticatedUserCanAddBookSuccessively ErrorException:尝试获取非对象的属性“client”
C:\wamp64\www\bookstore\vendor\laravel\passport\src\ClientRepository.php:89 C:\wamp64\www\bookstore\vendor\laravel\passport\src\PersonalAccessTokenFactory.php:71 C:\wamp64\www \bookstore\vendor\laravel\passport\src\HasApiTokens.php:67 C:\wamp64\www\bookstore\tests\Feature\BooksTest.php:20
当我运行 BooksTest 时
public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
{
$user = factory(User::class)->create();
$token = $user->createToken('bookbook')->accessToken;
$response = $this->withHeaders(['Authorization' => 'Bearer '.$token])
->json('POST', '/api/books', [
'title' => 'new book post',
'author' => 'new author',
'user_id' => $user->id
]);
$response->assertStatus(201);
}
Run Code Online (Sandbox Code Playgroud)
这是我第一次使用 PHPUnit 测试,我不知道为什么会收到此错误。我该如何让它发挥作用?
我目前正在学习如何使用 Laravel 应用程序编写 PHPUnit 测试,但几天来却遇到了困难。我的测试是,如果用户的 id 与图书的用户 id 相同,则仅允许经过身份验证的用户更新图书记录。
public function test_onlyAuthenticatedUserCanUpdateBookSuccessfully()
{
$user = factory(User::class)->create();
Passport::actingAs($user);
$book = factory(Book::class)->create();
dd($user, $book);
// $response = $this->json('PUT', '/api/books/'.$book->id, [
// 'id' => $book->id,
// 'title' => 'Updated book title',
// 'author'=> 'New Guy'
// ]);
// $response->assertStatus(201);
}
Run Code Online (Sandbox Code Playgroud)
但我最初遇到了 403 错误,在排除故障时,我从转储的数据中注意到创建的用户的 id 与书籍的 user_id 不同。
// Newly created user
#original: array:7 [
"name" => "Prof. Norwood Erdman"
"email" => "ihoeger@example.com"
"updated_at" => "2018-10-03 14:11:20"
"created_at" => "2018-10-03 14:11:20"
"id" => 2 …Run Code Online (Sandbox Code Playgroud) 我对 phpUnit 还是新手,无法使我的(非常简单的)测试工作。
<?php
use PHPUnit\Framework\TestCase;
class userTest extends TestCase {
public function testTrue() {
$this->assertTrue(true);
// This line wont work without autloader.php
$user = new User();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我需要从 autoloader.php 加载所有类:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="inc/autoload.php"></phpunit>
Run Code Online (Sandbox Code Playgroud)
但我在这些类中有很多 $SERVER 变量,比如
$_SERVER['REMOTE_ADDR']
$_SERVER['HTTPS']
$_SERVER['SERVER_NAME']
$_SERVER['DOCUMENT_ROOT']
$_SERVER['REQUEST_URI']
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
Notice: Undefined index: REMOTE_ADDR in /Applications/MAMP/htdocs/sakkadentrainer/classes/App.php on line 674
Run Code Online (Sandbox Code Playgroud)
我怎样才能让这些变量发挥作用?我更喜欢将它们“伪造”为 phpunit.xml 文件中的 env.variables,但我不知道这是否可能。
谢谢你的帮助!
我的设置:php 7.1.2、phpUnit 6.1.1、macOs Mojave、MAMP
我正在尝试模拟来自特定 api 的大量响应。
我的控制器代码如下所示(为简洁起见进行了修改):
class SomeClass
{
private $guzzle;
public function __construct(\GuzzleHttp\Client $guzzle) {
$this->guzzle = new $guzzle();
}
public function makeRequest(){
$client = $this->guzzle;
$url = 'http//somerurl';
$options = [];
$response = $client->request('POST', $url, $options);
return $response;
}
}
Run Code Online (Sandbox Code Playgroud)
测试看起来像这样(再次编辑)......
public function someTest(){
$mock = $this->createMock(\GuzzleHttp\Client::class);
$mock->method('request')->willReturn([
'response' => 'somedata'
]);
$someClass = new $SomeClass($mock);
$response = $someClass->makeRequest();
$body = $response->getBody();
...
}
Run Code Online (Sandbox Code Playgroud)
此时测试返回“Call to a member function getBody on null”;
如何测试 guzzle 调用的 getBody 响应?
先感谢您...
测试开始于 \xe4\xb8\x8b\xe5\x8d\x885:45 ...
\n/usr/local/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9001 -dxdebug.remote_host=127.0.0.1 /var/www/example/vendor/phpunit/phpunit/phpunit --no-configuration --filter "/(::testMerlinTemplate)( .*)?$/" tests\\jobs\\SettlementJobTest /var/www/example/tests/unit/jobs/SettlementJobTest.php --teamcity\nPHPUnit 7.1.4 by Sebastian Bergmann and contributors.\n\n\nCodeception\\Exception\\InjectionException : Service di is not defined and can't be accessed from a test\n /var/www/example/vendor/codeception/base/src/Codeception/Test/Metadata.php:191\n /var/www/example/vendor/codeception/base/src/Codeception/Test/Unit.php:47\nRun Code Online (Sandbox Code Playgroud)\n 我在 Laravel 中使用 Phpunit,我的 Api 有多个可接受的响应。我有两种情况的问题:
1-响应结构可以是以下两种之一:
$response->assertJsonStructure(['cities'=>[]]);
or
$response->assertJsonStructure(['cities'=>[['id','name']]])
Run Code Online (Sandbox Code Playgroud)
2-响应状态可以是200或302
$response->assertStatus(200);
or
$response->assertStatus(302);
Run Code Online (Sandbox Code Playgroud)
但我找不到任何方法来“或”这两个条件。
我正在寻找这样的东西:
$response->assertOr(
$response->assertStatus(200),
$response->assertStatus(302)
);
Run Code Online (Sandbox Code Playgroud) 我有一个类,它使用 Laravel 的全局 event() 函数在模型更改时触发单个事件。我能够防止在单元测试期间触发此事件的唯一方法是实际命名空间并在测试本身中声明一个新的 event() 函数并使其不执行任何操作。它有效,但对我来说似乎不是一个很好的解决方案。我查看了 Laravel 文档,发现有些人在测试中成功使用了 Event::fake() ,但是当我尝试这样做时,我得到:
BadMethodCallException: Method Mockery_0_Illuminate_Contracts_Events_Dispatcher::until() does not exist on this mock object
Run Code Online (Sandbox Code Playgroud)
我使用的是 Laravel 5.4。有没有更干净的方法来防止在测试期间触发此事件?我真的不喜欢声明一个空的命名空间 event() 函数的想法。
编辑:
我正在测试的类是 UserDomain 类。在逻辑的一部分中,它调用 Laravel 的全局 event() 方法:
event(new RoleChanged($this->user));
Run Code Online (Sandbox Code Playgroud)
为了在测试中抑制这种情况的发生,我尝试了 Event::fake() 并且还尝试使用 Trait WithoutEvents 及其 withoutEvents() 方法。两者都不起作用,并且两次都会出现我上面提到的相同错误。
phpunit ×10
php ×7
laravel ×6
laravel-5.6 ×2
codeception ×1
console ×1
guzzle6 ×1
json ×1
laravel-5 ×1
laravel-5.5 ×1
mocking ×1
php-7 ×1