我目前有一个Socket类,它基本上只是PHP socket_*函数的OO包装类:
class Socket {
public function __construct(...) {
$this->_resource = socket_create(...);
}
public function send($data) {
socket_send($this->_resource, $data, ...);
}
...
}
Run Code Online (Sandbox Code Playgroud)
我不认为我可以模拟套接字资源,因为我使用PHP的套接字函数,所以现在我不知道如何可靠地单元测试这个类.
我有读取器类从stdin读取并返回readed值.
class Reader
{
const STREAM_READ = 'php://stdin';
private $_streamHandle;
public function __construct($stream = self::STREAM_READ)
{
$this->_streamHandle = fopen($stream, 'r');
}
public function getReadedValue()
{
$value = trim(fgets($this->_streamHandle));
return $value;
}
public function __destruct()
{
fclose($this->_streamHandle);
}
}
Run Code Online (Sandbox Code Playgroud)
现在是我的问题,我如何测试这个类,从stdin读取一些东西并按getReadedValue()函数返回readed值?
我对Zend和单元测试都很陌生.我想出了一个使用Zend Framework 2和Doctrine的小应用程序.它只有一个模型和控制器,我想对它们运行一些单元测试.
这是我到目前为止所拥有的:
基础学说"实体"类,包含我想在所有实体中使用的方法:
<?php
/**
* Base entity class containing some functionality that will be used by all
* entities
*/
namespace Perceptive\Database;
use Zend\Validator\ValidatorChain;
class Entity{
//An array of validators for various fields in this entity
protected $validators;
/**
* Returns the properties of this object as an array for ease of use. Will
* return only properties with the ORM\Column annotation as this way we know
* for sure that it is a column with data …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一些测试.
这是我的测试类:
class ExampleTest extends TestCase {
public function setUp()
{
parent::setUp();
Artisan::call('migrate');
$this->seed();
Auth::loginUsingId(1);
}
public function testActionUpdateNew()
{
$action = new Action(Array());
$action->save();
var_dump($action->id);
Action::with('reponses','contact','user','etudiant','entreprise','etude')->findOrFail($action->id);
}
public function testEtudes()
{
$etudes=Etude::all()->toArray();
$this->assertCount(10, $etudes, "Nombre d'études incorrectes");
$numEtudes=count($etudes);
//Buggy part
$etude= Etude::create(Array());
var_dump($etude->id);
$etudes=Etude::all()->toArray();
$this->assertCount(11, $etudes, "Nombre d'études incorrectes");
//10+1 should equal to 11 but it hasnt updated
}
}
Run Code Online (Sandbox Code Playgroud)
没有通过的测试是第二个:我计算开头的10个雄辩的对象练习曲的数量,然后我在数据库中添加一个练习曲(使用Etude :: create()),创建对象,因为$ etude-> id给出了一个实数.但是,练习曲的数量还没有更新.
当我从Action :: with('reponses',...中)的热切加载中删除'etude'时,问题确实消失了
这是Action类中的练习曲关系:
public function etude() {
return $this->belongsTo('Etude');
}
Run Code Online (Sandbox Code Playgroud)
你们有没有想过如果laravel中的急切加载会有这种奇怪的行为以及如何解决这个问题?
我发现用('etude')调用可以删除注册到Eloquent模型的事件: …
我的其中一条路线中有以下代码:
return Response::download('cv.pdf');
知道如何测试这个吗?我试过使用 shouldReceive() 但这似乎不起作用('shouldReceive() 未定义函数......')。
我想设置Bamboo CI Server.我创建了两个阶段:
第1阶段没问题,但在第2阶段我有错误.在构建日志中我有:
Starting task 'PHPUnit Testing' of type 'com.atlassian.bamboo.plugins.php:task.builder.phpunit'
12-pa?-2014 10:45:49
Beginning to execute external process for build 'CCP - CI - Unit Testing Build - Default Job #4 (CCPCI-UTB-JOB1-4)'
... running command line:
/usr/local/bin/phpunit --log-junit test-reports/phpunit.xml --coverage-html test-reports/coverage/html --bootstrap /var/www/html/ccp/core/tests/bootstrap.php --no-configuration /var/www/html/ccp/core/tests
... in: /home/bamboo/bamboo_home/xml-data/build-dir/CCPCI-UTB-JOB1
12-pa?-2014 10:45:49 X-Powered-By: PHP/5.5.11
12-pa?-2014 10:45:49 Content-type: text/html
12-pa?-2014 10:45:49
12-pa?-2014 10:45:49 Failing task since text 'OK' was not found in last 250 log entries
12-pa?-2014 10:45:49 Parsing test results... …Run Code Online (Sandbox Code Playgroud) 我已经搜索并阅读了文档,或者至少我认为我已经阅读过,但是我一直无法找到是否有办法使用 PHPUNIT 获取所有跳过的测试的列表?
这可能吗?
PHP 7.4 和 PHPUnit 9
使用 PHPUnit 主页示例 ( https://phpunit.de/getting-started/phpunit-9.html ):
private function ensureIsValidEmail(string $email): void
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
sprintf(
'"%s" is not a valid email address',
$email
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
主页还向我们展示了如何使用expectException()方法来测试抛出的异常:
public function testCannotBeCreatedFromInvalidEmailAddress(): void
{
$this->expectException(InvalidArgumentException::class);
Email::fromString('invalid');
}
Run Code Online (Sandbox Code Playgroud)
那太棒了。但是,如果我想测试在给定有效输入的情况下是否抛出异常怎么办?
查看文档(https://phpunit.readthedocs.io/en/9.3/writing-tests-for-phpunit.html#testing-exceptions)似乎没有提到逆向方法expectException() ?
我应该如何处理这个问题?
编辑添加:
为了完全清楚地表明,我正在测试一个场景,即不会Email::fromString('valid.email@example.com');引发异常。
我的类中有一个方法(getUsers()),我想模拟它,但我的类中有一个构造函数。在模拟我的类时如何将值传递给构造函数?
class MyNotifications {
/**
* Date time.
*
* @var DateTime|mixed|null
*/
public $date;
public function __construct($date = NULL)
{
if (!$date) {
$date = new \DateTime();
}
$this->date = $date;
}
/**
* Get users.
*
* @param int $node_id
* Node id.
*
* @return mixed
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function getUsers($node_id)
{
// API code goes here.
}
/**
* Get day.
*
* @return false|int|string
*/
public function getDay()
{
return $this->date->format('d'); …Run Code Online (Sandbox Code Playgroud) 使用 Symfony 5.2 和 PhpUnit 最新版本,我的功能测试出现此错误
LogicException: You cannot create the client used in functional tests if the "framework.test" config is not set to true.
Run Code Online (Sandbox Code Playgroud)
内容config/packages/test/framework.yaml:
framework:
test: true
session:
storage_id: session.storage.mock_file
Run Code Online (Sandbox Code Playgroud)
我的 PHP 部分phpunit.xml.dist:
<php>
<ini name="error_reporting" value="-1"/>
<server name="APP_ENV" value="test" force="true"/>
<server name="SHELL_VERBOSITY" value="-1"/>
<env name="BOOTSTRAP_CLEAR_CACHE_ENV" value="test"/>
</php>
Run Code Online (Sandbox Code Playgroud)
这是我的测试内容:
class JWTTokenAuthenticatorTest extends WebTestCase
{
public function test_authentication_token()
{
$client = static::createClient();
$client->request(
'POST',
'/authentication_token',
[],
[],
['CONTENT_TYPE' => 'application/json'],
'{"email":"api@api.com","password":"api"}'
);
$this->assertResponseIsSuccessful();
$this->assertMatchesRegularExpression('/{"token":"(.*)"}/i', $client->getResponse()->getContent()); …Run Code Online (Sandbox Code Playgroud)