【问题标题】:How can I test a class that extends another class in PHP?如何测试扩展 PHP 中另一个类的类?
【发布时间】:2022-01-13 18:58:53
【问题描述】:

我是 PHPUnit 的新手,我目前正在尝试测试一个对系统上的用户进行身份验证的函数。该函数名为authenticate(),位于Account 类中。

测试

public function passwordAreNotTheSame_Test()
{
    require 'login/app/models/Account.php';
    require 'login/app/controllers/Pages.php';
    require 'login/lib/Controller.php';

    $pages = new Pages();
    $account = new Account($pages);
    $username = "test_name";
    $password = "test_password";
    $cpassword = "invalid_password";
    $email = "email@test.com";
    $Expected = "Passwords do not match!";
    $Received = $account->register($username, $password, $cpassword, $email);
    
    $this->assertEquals($Expected, $Received);
}

但是,我的问题是Account 类中的构造函数还需要一个名为Pages 的控制器。我的问题是位于文件Pages.php 中的类Pages, 扩展了类Controller。像这样:

class Pages extends Controller {
    // some code
}

所以当我运行测试时,我遇到了以下问题。

错误:找不到类“控制器” C:\xampp\htdocs\apex-management\login\app\controllers\Pages.php:3 C:\xampp\htdocs\apex-management\tests\Unit\RegisterAccountTests.php:13 时间:00:00.019,内存:8.00 MB

错误!测试:1,断言:0,错误:1。进程完成并退出 代码2

我怎样才能使这个测试工作?我想学习如何使用 PHPUnit,但我在网上找不到此类问题的文档。

【问题讨论】:

  • 检查Controller类在哪里,他找不到它,需要正确的路径。
  • 您没有正确要求包含 Controller 类的文件。如果您没有设置某种自动加载器,您应该在Pages 代码文件中执行require 语句。
  • 你使用的是哪个 Laravel 版本,你使用什么命令来运行测试? Laravel 已经设置了测试,并且控制器应该能够在不需要显式要求的情况下自动加载。

标签: php unit-testing phpunit


【解决方案1】:

在 php oop 中,它支持 'extends' 关键字。这是一个例子

<?php
class parent{
   //parent class definition
}

class child extends parent{
   //child class declarations
}

?> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    相关资源
    最近更新 更多