标签: phpunit

如何使用 PHPUnit 的 setExpectedException()?

使用 PHPUnit,我可以成功测试对类的特定调用是否正确引发了如下异常:

try 
{
    $dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn');   
}
catch (Exception $ex) 
{
    return;
}
$this->fail("Import_Driver_Excel::get_file_type_from_file_name() does not properly throw an exception");
Run Code Online (Sandbox Code Playgroud)

但我在这里读到有一种更简单的方法,基本上在一行中使用setExpectedException():

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->setExpectedException('InvalidArgumentException');
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我如何让它像上面的例子一样工作,即我想测试这个类是否只有在我用“BAD_NAME.nnn”进行特定调用时才会抛出这个异常?这些变体不起作用:

$dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn');  
$this->setExpectedException('Exception');
Run Code Online (Sandbox Code Playgroud)

也不是这个:

$this->setExpectedException('Exception');
$dummy = Import_Driver_Excel::get_file_type_from_file_name('BAD_NAME.nnn'); 
Run Code Online (Sandbox Code Playgroud)

如何使用 setExpectedException() 替换上面的工作示例?

php phpunit

6
推荐指数
1
解决办法
8992
查看次数

PHPUnit 错误 - 找不到类

我刚刚在我的系统上安装了 PHPUnit 3.5,从 3.4 升级它,但我在使用新版本时遇到了一些问题。当我尝试运行测试时,我总是得到相同的输出。这是我尝试在命令行上运行StackTestPHPUnit 手册中的示例时得到的结果,示例 4.1:

> phpunit StackTest

X-Powered-By: PHP/5.2.17
Content-type: text/html

PHPUnit 3.5.13 by Sebastian Bergmann.

Class StackTest could not be found in StackTest.php.
Run Code Online (Sandbox Code Playgroud)

更糟糕的是,当我尝试从 Web 浏览器运行它时,我得到以下输出:

Fatal error: Class 'PHPUnit_Framework_TestCase' not found in /path/to/tests/StackTest.php on line 2 
Run Code Online (Sandbox Code Playgroud)

有谁知道如何设置?谢谢。

php phpunit

6
推荐指数
2
解决办法
9244
查看次数

如何使 SonarQube PHP 插件与 PHPUnit 一起使用?

我已经安装了 jenkins 和 SonarQube Runner 2.4、SonarQube Server 5.1.2、php 插件 2.6、phpunit5.1,然后我使用独立的声纳分析运行,这是我的配置:

sonar.language=php
sonar.projectVersion=1.0
sonar.sourceEncoding=UTF-8

sonar.phpCodesniffer.timeout=120
sonar.projectKey=xxx
sonar.projectName=xxxx
sonar.sources=.
sonar.tests=./tests/tests/
Run Code Online (Sandbox Code Playgroud)

这是控制台输出:

$ /apps/svr/sonar-runner/bin/sonar-runner -e -Dsonar.projectBaseDir=/home/apps/.jenkins/workspace/pc_dev_example -Dsonar.sourceEncoding=UTF-8 -Dsonar.sources=. -Dsonar.language=php -Dsonar.projectVersion=1.0 -Dsonar.projectKey=php:pc_dev_example -Dsonar.phpUnit.argumentLine="/apps/svr/sonar" -Dsonar.inclusions=applications/vipuser/public/passport.php -Dsonar.phpCodesniffer.timeout=120 -Dsonar.tests=./tests/tests/ -Dsonar.projectName=pc_dev_example
SonarQube Runner 2.4
Java 1.7.0_71 Oracle Corporation (64-bit)
Linux 2.6.32-504.23.4.el6.x86_64 amd64
INFO: Error stacktraces are turned on.
INFO: Runner configuration file: /apps/svr/sonar-runner/conf/sonar-runner.properties
INFO: Project configuration file: NONE
INFO: Default locale: "en_US", source code encoding: "UTF-8"
INFO: Work directory: /home/apps/.jenkins/workspace/pc_dev_example/.sonar
INFO: SonarQube Server 5.1.2
15:56:42.207 INFO  - Load …
Run Code Online (Sandbox Code Playgroud)

php phpunit sonarqube

6
推荐指数
2
解决办法
1万
查看次数

Laravel API 测试 - 如何测试具有外部 API 调用的 API

我的 API 代码

public function store (Request $request, $profileId)
{
    $all = $request->all();
    $token = AccessToken::with('users')->where('access_token',$request->input('access_token'))->first();

    if($token && $token->users->isOwnProfile($profileId))
    {
        $rules = [
            'access_token'     => 'required',
            'title'            => 'required',
            'description'      => 'required',
            'file_id'          => 'required',
            'audience_control' => 'required|in:' . join(',', PostRepository::$AUDIENCE_CONTROL),
            'tags'             => 'required',
        ];
        $validator = Validator::make($all, $rules);

        $error = $validator->errors()->toArray();
        if ($validator->fails())
        {
            return $this->setStatusCode(401)
                ->setStatusMessage(trans('api.validation failed'))
                ->respondValidationMessage($error);
        }
        try {
            $response = $this->postRepository->save($request, $profileId);
            if(isset($response['error']))
                return $this->messageSet([
                    'message' => $response['error']['message'],
                ], $response['error']['status_code']);

            return $this->setDataType('post_id')
                ->setStatusCode('200')
                ->respondWithCreatedId(trans('api.Post created'), …
Run Code Online (Sandbox Code Playgroud)

api phpunit unit-testing laravel laravel-5.2

6
推荐指数
1
解决办法
3825
查看次数

PHPUnit如何测试包含check_admin_referer()的Wordpress函数?

我刚开始用Wordpress学习PHPUnit.我有一个插件可以从change.org获取请愿数据.其中一个管理类函数验证来自Wordpress管理区域的设置,并在此验证过程中调用`check_admin_referer().

  public function sc_validate_settings() {
    //check nonce field is valid
    check_admin_referer($this->plugin_name, 'security');    

    //get new settings 
    $settings = $this->sc_clean_new_settings();

    //validate url
    $valid_url = $this->sc_validate_url($settings['petition_url']);

    //validate api_key
    $valid_api_key = $this->sc_validate_api_key($settings['petition_api_key']);

    if ($valid_url && $valid_api_key) {

      $this->clean_settings = $settings;
      return true;

    }

    return false;

  }
Run Code Online (Sandbox Code Playgroud)

如果我注释掉,那么这个PHPUnit测试会通过,check_admin_referer()但如果没有,我就无法通过.

  public function testValidateSettings() {    

    $this->assertTrue($this->plugin_admin->sc_validate_settings());

  }  
Run Code Online (Sandbox Code Playgroud)

我已经尝试手动设置一个nonce,action和_wp_http_referer,并在tests/bootstrap.php和测试类本身中通过wp_nonce_field()via $_POST.我已经阅读了一些关于模拟对象/方法的内容,但是在这个实例中并没有看到它们如何被使用.

我可能完全误解了所有这些是如何工作的,但任何帮助将不胜感激!

php wordpress phpunit

6
推荐指数
1
解决办法
814
查看次数

如何对构造函数采用一些参数的类的方法进行单元测试?

我有一类形式是这样的:

class A{  
    public function __constructor(classB b , classC c){
    //
    }

    public function getSum(var1, var2){
        return var1+var2;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试用例类是这样的:

use A;   
class ATest extends PHPUnit_Framework_TestCase{  

    public function testGetSum{  
        $a = new A();
        $this->assertEquals(3, $a->getSum(1,2));  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

但是,当我运行 phpunit 时,它会引发一些错误,例如:

Missing argument 1 for \..\::__construct(), called in /../A.php on line 5

即使我提供了参数,它也会抛出相同的错误,但在不同的文件中。
说,我实例化 $a = new A(new classB(), new classC());

然后,我得到了 classB 的构造函数的相同错误(classB 的构造函数与 A 的构造函数具有相似的形式)。

Missing argument 1 for \..\::__construct(), called in /../B.php on line 10

有没有其他方法,我可以测试功能或我缺少的东西。

我不想使用模拟 …

php phpunit constructor unit-testing symfony

6
推荐指数
2
解决办法
9625
查看次数

PHPUnit:如何模拟具有多个参数且没有直接顺序的多个方法调用?

我需要测试以下功能:

[...]
public function createService(ServiceLocatorInterface $serviceManager)
{

    $firstService = $serviceManager->get('FirstServiceKey');
    $secondService = $serviceManager->get('SecondServiceKey');

    return new SnazzyService($firstService, $secondService);
}
[...]
Run Code Online (Sandbox Code Playgroud)

我知道,我可以这样测试:

class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testReturnValue()
    {
        $firstServiceMock = $this->createMock(FirstServiceInterface::class);
        $secondServiceMock = $this->createMock(SecondServiceInterface::class);

        $serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);

        $serviceManagerMock->expects($this->at(0))
             ->method('get')
             ->with('FirstServiceKey')
             ->will($this->returnValue($firstService));

        $serviceManagerMock->expects($this->at(1))
             ->method('get')
             ->with('SecondServiceKey')
             ->will($this->returnValue($secondServiceMock));

        $serviceFactory = new ServiceFactory($serviceManagerMock);

        $result = $serviceFactory->createService();
    }
    [...]
Run Code Online (Sandbox Code Playgroud)

或者

[...]
public function testReturnValue()
{
    $firstServiceMock = $this->createMock(FirstServiceInterface::class);
    $secondServiceMock = $this->createMock(SecondServiceInterface::class);

    $serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);

    $serviceManagerMock->expects($this->any())
         ->method('get')
         ->withConsecutive(
            ['FirstServiceKey'],
            ['SecondServiceKey'],
         )
         ->willReturnOnConsecutiveCalls(
            $this->returnValue($firstService),
            $this->returnValue($secondServiceMock)
         ); …
Run Code Online (Sandbox Code Playgroud)

phpunit unit-testing zend-framework2

6
推荐指数
1
解决办法
671
查看次数

PHPUnit 数据提供程序参数计数错误

我刚刚开始使用PHPUnit. 到目前为止,除了Data Provider问题之外,一切都在进行中。

问题是当我运行测试时,它通过了。但是如果我再次运行它,它会失败并出现以下错误:

ArgumentCountError: Too few arguments to function ValidationTest::testValidateType(), 0 passed and at least 3 expected
Run Code Online (Sandbox Code Playgroud)

如果我对数据提供程序函数进行任何更改(即更改要返回的数据、提供程序函数名称等)并重新运行,它会通过一次并在所有连续测试运行中失败并出现上述错误。

我正在使用最新版本的 PHPUnit(一小时前更新)。不幸的是,我没有在任何地方找到任何特定的解决方案。所以,我真的很担心,我是不是犯了非常愚蠢的错误?

不确定,但 PHPUnit 是否使用任何缓存机制来缓存提供者数据?如果是,那么有什么方法可以清洁它(可能使用setUp或tearDown)?

期待专家的意见。提前致谢。:-)


以下代码工作一次(通过一次):

/**
 * @covers Validation
 * @coversDefaultClass Validation
 */
class ValidationTest extends TestCase {

    protected $validation;


    protected function setUp() {
        $this->validation = new Validation();
    }


    /**
     * @covers ::validateType
     * @dataProvider validateTypeProdiver
     */
    public function testValidateType($assertion, $argument, $type) {
        $result = $this->validation->validateType($argument, $type);

        switch ($assertion) {
            case …
Run Code Online (Sandbox Code Playgroud)

php testing phpunit unit-testing

6
推荐指数
1
解决办法
3064
查看次数

Laravel 工厂关系...尊重 create() 或 make()

根据 Laravel关于在模型工厂中定义关系的文档:

您还可以使用工厂定义中的闭包属性将关系附加到模型。例如,如果您想在创建 Post 时创建一个新的 User 实例,您可以执行以下操作:

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph,
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        }
    ];
});
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是create()关系定义中的引用。在我看来,这不属于这里。

如果我想保留与数据库的关系,它会很好用:

factory(App\Post::class)->create();
Run Code Online (Sandbox Code Playgroud)

通过直接运行上面的代码,一个新的App\Post和一个新的App\User将被创建并持久化到数据库中。

但是,如果我只想new启动模型而不是通过运行将任何东西(根本)持久化到数据库中:

factory(App\Post::class)->make();
Run Code Online (Sandbox Code Playgroud)

它在某种程度上做我想做的事。一个新的App\Post实例被创建但不持久化,但是App\Comment被创建并持久化到数据库中。


在我看来,我真正想要的是这样的:

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph,
        'user_id' => function () {
            // here I only want to declare the relationship,
            // …
Run Code Online (Sandbox Code Playgroud)

php phpunit laravel eloquent

6
推荐指数
1
解决办法
2327
查看次数

SQLite SQLSTATE[HY000]:一般错误:8 尝试写入只读数据库

我正在使用 SQLite 连接和学说迁移对 PHPUnit 进行功能测试。我在setUp方法中从头开始进行数据库迁移:

public function setUp()
{
    parent::setUp();
    
    @unlink(__DIR__ . '/../../../../../../../var/sqlite.db');

    exec('./vendor/bin/doctrine-migrations migrations:migrate --db-configuration=migrations-db-test.php --configuration=migrations_test.yml --no-interaction');
}
Run Code Online (Sandbox Code Playgroud)

然后我可以从数据库写入/读取。例如:

public function test_add_event_should_add_event()
{
    $service = $this->getAdEventComparativesUpdateService();
    $request = AdEventComparativesUpdateServiceRequest::make(self::AD_ID, self::USER_IP);
    $response = $service->execute($request);

    $this->assertEquals(1, $response->getTotal());
}
Run Code Online (Sandbox Code Playgroud)

它有效。即使我使用相同的参数调用两次服务,它也确实有效。在这种情况下,它只需要在第一次写入:

public function test_add_two_same_events_should_add_one_event()
{
    $service = $this->getAdEventComparativesUpdateService();
    $request = AdEventComparativesUpdateServiceRequest::make(self::AD_ID, self::USER_IP);
    // Call twice
    $service->execute($request);
    $response = $service->execute($request);

    $this->assertEquals(1, $response->getTotal());
}
Run Code Online (Sandbox Code Playgroud)

当我必须测试两个必须同时编写的调用时,问题就出现了:

public function test_add_two_different_events_should_add_two_events()
{
    $service = $this->getAdEventComparativesUpdateService();
    $request = AdEventComparativesUpdateServiceRequest::make(self::AD_ID, self::USER_IP);
    $response = $service->execute($request);

    $service = $this->getAdEventComparativesUpdateService();
    $request …
Run Code Online (Sandbox Code Playgroud)

php sqlite phpunit doctrine doctrine-migrations

6
推荐指数
1
解决办法
945
查看次数