【问题标题】:How do I use PHPUnit to test __construct with arguments?如何使用 PHPUnit 测试带参数的 __construct?
【发布时间】:2021-04-07 21:15:32
【问题描述】:

我是 PHPUnit 和一般单元测试的新手。我似乎找不到关于如何最好地进行测试的明确教程或资源:

  1. 不传递参数失败。
  2. 如何为构造函数测试传递参数。
  3. 传递空参数会导致预期的异常。

我将如何测试这个构造函数?

<?php

class SiteManagement {
    public function __construct (array $config) {
        // Make sure we actually passed a config
        if (empty($config)) {
            throw new \Exception('Configuration not valid', 100);
        }

        // Sanity check the site list
        if (empty($config['siteList'])) {
            throw new \Exception('Site list not set', 101);
        }
    }
}

【问题讨论】:

  • 新站点管理($configarray);

标签: php unit-testing phpunit


【解决方案1】:

PHPUnit 文档的example 2.11 展示了如何测试异常。

对于您的特定班级,可能是这样的:

$this->expectException(Exception::class);

$object = new SiteManagement([]);

除非这些参数是可选的,否则您不应该测试方法是否在没有参数的情况下失败。这超出了单元测试的范围。

【讨论】:

    【解决方案2】:

    适合您班级的良好测试电池是:

    /** @test */
    public function shouldFailWithEmptyConfig(): void
    {
        $config = [];
    
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Configuration not valid');
        $this->expectExceptionCode(100);
    
        new SiteManagement($config);
    }
    
    /** @test */
    public function shouldFailWithoutSiteListConfig(): void
    {
        $config = ['a config'];
    
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Site list not set');
        $this->expectExceptionCode(101);
    
        new SiteManagement($config);
    }
    
    /** @test */
    public function shouldMakeAFuncionality(): void
    {
        $config = [
            'siteList' => '',
        ];
    
        $siteManagement = new SiteManagement($config);
    
        self::assertSame('expected', $siteManagement->functionality());
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 2019-10-22
      • 2015-03-26
      • 2018-05-28
      • 2015-04-02
      • 2011-03-23
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多