PHP单元测试封闭功能
我正在应用程序中执行单元测试,其中一些功能包括闭合功能,如下所示:
<?php
namespace JobProgress\Transformers;
use League\Fractal\TransformerAbstract;
class CustomersTransformer extends TransformerAbstract {
public function includesCreatedBy($customer) {
$user = $customer->createdBy;
if($user) {
return $this->item($user, function($user){
\Log::info('unit test');
return [
'id' => (int)$user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'full_name' => $user->full_name,
'full_name_mobile' => $user->full_name_mobile,
'company_name' => $user->company_name,
];
});
}
}
}
注意:我已经扩展了分形的transformerabstract类,并将项目函数用作transfsererabstract类中的$ this- this-this-this-this。
这是我执行测试的方式:
public function testIncludeDeletedBy() {
$customer = factory(Customer::class)->create();
$include = $this->transformer->includesCreatedBy($customer);
$object = $include->getData()->first();
$this->assertInstanceOf(User::class, $object);
}
我的单位测试没有执行我在闭合功能中编写的代码。 就像我在上面代码中提到的那样,我添加了一些日志,但是我的单元测试没有执行代码的部分。
任何人都可以帮我吗
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能与
$ this-&gt; item()
方法的实现细节有关。您可能希望在我们看到的情况下执行关闭,仅需要解析闭合,然后将其作为参数传递给该方法。该代码没有任何实际执行的代码,因此您不应该期望它是一个实现细节,而不是在您的测试中。
您可以将闭合匿名化并直接调用,以便能够将其作为一个单位进行测试。
因此,您对现有方法中的if-sause进行了一项测试,并且一项测试可以使您运行(不仅解析)您当前拥有的代码作为匿名函数 /闭合。
有时称为A 测试点,可以提高您的速度。您拥有的单元越小,测试它们就越容易。
对于三个点
(...)
,这是PHP 8.1语法,比较对于 callables 的8.1之前的替代性php语法,例如:This might be related to the implementation detail of the
$this->item()
method. You may expect the closure to be executed while as we can see, the closure only needs to be parsed and then passed to the method as a parameter.The code shows nothing that it is actually executed and therefore you should not expect this to be as it is an implementation detail not under your test.
You could de-anonymize the closure and call it directly to be able to test it as a unit.
So you have one test for the if-clause in the existing method and one test which allows you to run (not only parse) the code you currently have as an anonymous function / closure.
This is sometimes called a test-point and can bring you up speed. The smaller the units you have are, the easier it is to test them.
For the three dots
(...)
, this is PHP 8.1 syntax, compare PHP RFC: First-class callable syntax for alternative PHP syntax before 8.1 for callables, e.g.: