标签: phpunit

PHPUnit等于带有delta的日期

我在PHPUnit中遇到了一个问题,我想在比较日期时在equalTo方法中使用delta参数.假设我想将日期视为相等,如果它们的差异不超过10秒.$ some_delta的适当价值是多少?10?10000?还是完全不同的东西?

$this->_restClient->expects($this->at(0))
    ->method('getData')
    ->with(
        $this->equalTo(array('1')),
        $this->equalTo(array('2')),
        $this->equalTo($this->_date, $some_delta),
        $this->equalTo(null),
    )
    ->will($this->returnValue($this->_restResponses['generalRestResponse']));
Run Code Online (Sandbox Code Playgroud)

php phpunit

23
推荐指数
3
解决办法
1万
查看次数

对类的构造函数调用的方法进行存根

如何在PHPUnit中存根一个由test的构造函数中的类调用的方法?例如,下面的简单代码将无法工作,因为在我声明存根方法时,已经创建了存根对象,并且我的方法被调用,取消存储.

要测试的类:

class ClassA {
  private $dog;
  private $formatted;

  public function __construct($param1) { 
     $this->dog = $param1;       
     $this->getResultFromRemoteServer();
  }

  // Would normally be private, made public for stubbing
  public getResultFromRemoteServer() {
    $this->formatted = file_get_contents('http://whatever.com/index.php?'.$this->dog);
  }

  public getFormatted() {
    return ("The dog is a ".$this->formatted);
  }
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

class ClassATest extends PHPUnit_Framework_TestCase {
  public function testPoodle() {  
    $stub = $this->getMockBuilder('ClassA')
                 ->setMethods(array('getResultFromRemoteServer'))
                 ->setConstructorArgs(array('dog52'))
                 ->getMock();

    $stub->expects($this->any())
         ->method('getResultFromRemoteServer')
         ->will($this->returnValue('Poodle'));

    $expected = 'This dog is a Poodle';
    $actual = $stub->getFormatted();
    $this->assertEquals($expected, $actual);
  }
}
Run Code Online (Sandbox Code Playgroud)

php phpunit

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

预期异常后,PHPUnit不会继续测试

为什么PHPUnit不会在此代码中执行最后的异常断言?

public function testConfigOverriding()
{
    $this->dependencyContainer = new DependencyContainer(__DIR__ . "/../../Resources/valid_json.json");
    $this->assertEquals('overriden', $this->dependencyContainer->getConfig('shell_commander')['pygmentize_command']);

    $unexisting = "unexisting_file";
    $this->setExpectedException('Exception', "Configuration file at path \"$unexisting\" doesn't exist.");
    $this->dependencyContainer = new DependencyContainer($unexisting);

    $invalid = __DIR . "/../../Resources/invalid_json.json";
    $this->setExpectedException('Exception', "Configuration JSON file provided is not valid.");
    $this->dependencyContainer = new DependencyContainer($invalid);
}
Run Code Online (Sandbox Code Playgroud)

所以基本上:它测试是否抛出了"unexsisting_file"异常,但完全忽略了"无效的json"测试.我是否需要为每个抛出的异常进行单独的测试?

php phpunit exception

22
推荐指数
3
解决办法
7160
查看次数

在PHPUnit中使用名称空间时"找不到类"

我是PHPUnit的新手,在设置它以访问我的PHP文件时遇到了一些麻烦.我用于我的应用程序的目录结构是这样的:

./phpunit.xml

./lib/Application/
  -> Dir1/File1.php (namespace = Application\Dir1)
  -> Dir1/File2.php
  -> Dir2/File1.php (namespace = Application\Dir2)

./tests/Application/Tests
  -> Test1.php (namespace = Application\Tests)
  -> Test2.php 
Run Code Online (Sandbox Code Playgroud)

在我的PhpUnit.xml中,我有:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit verbose="false">
  <testsuites>
      <testsuite name="Application">
          <directory>./tests/Application/Tests</directory>
      </testsuite>
  </testsuites>
  <logging>
       <log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
       <log type="json" target="/tmp/phpunit-logfile.json"/>
  </logging>
  <filter>
        <whitelist>
            <directory suffix=".php">./lib</directory>
        </whitelist>
  </filter>
</phpunit>
Run Code Online (Sandbox Code Playgroud)

在我的一个测试文件中,我打开:

namespace Application\Tests;

use Application\Dir1\File1;

class MyTest extends File1 {}
Run Code Online (Sandbox Code Playgroud)

但它继续说:

找不到类'Application\Dir1\File1'

我哪里错了?

php phpunit namespaces

22
推荐指数
2
解决办法
3万
查看次数

如何在Laravel 5中为phpunit指定不同的.env文件?

我有一个.env包含我的数据库连接详细信息的文件,正如Laravel 5一样.我想覆盖这些用于测试,我可以做phpunit.xml.然而,这样做似乎违背了.env不提交环境配置,特别是密码的哲学.

有没有可能有类似的东西,.env.testing并告诉phpunit.xml从中读取?

php phpunit laravel laravel-5 phpdotenv

22
推荐指数
5
解决办法
2万
查看次数

phpunit:如何在测试之间传递值?

我真的碰到了这堵砖墙.如何在phpunit中的测试之间传递类值?

测试1 - >设定值,

测试2 - >读取值

这是我的代码:

class JsonRpcBitcoinTest extends PHPUnit_Framework_TestCase
{
    public function setUp(){
        global $configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort;

        $this->bitcoindConn = new JsonRpcBitcoin($configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort);
        $this->blockHash = '';
    }

    /**
    * @depends testCanAuthenticateToBitcoindWithGoodCred
    */
    public function testCmdGetBlockHash()
    {   
        $result = (array)json_decode($this->bitcoindConn->getblockhash(20));
        $this->blockHash = $result['result'];
        $this->assertNotNull($result['result']);
    }

    /**
    * @depends testCmdGetBlockHash
    */
    public function testCmdGetBlock()
    {   
        $result = (array)json_decode($this->bitcoindConn->getblock($this->blockHash));
        $this->assertEquals($result['error'], $this->blockHash);
    }
}
Run Code Online (Sandbox Code Playgroud)

testCmdGetBlock()没有得到$this->blockHash应该设置的值testCmdGetBlockHash().

非常感谢帮助理解错误.

phpunit class

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

Laravel 5.2 | 测试UploadedFile在Post之后错过$ test值.错误?

更新2016/04/26 11:30 GMT + 2解决方法

从Laravel 5.2.15开始,$ test参数被删除,但没有明确的原因,因为Symfony的UploadedFile仍然有$ test参数.

解决方法是暂时使用Laravel 5.2.14.

更新2016/04/26 11:00 GMT + 2

Laravel自己的UploadedFile没有传递$ test参数.查看这些资源:

我知道,还有另一个问题:如何在Laravel 5.2中测试文件上传,但标记的答案对我不起作用.

测试用例

我创建了一个Symfony的UploadedFile类的实例,我设置$testtrue.我将文件发布到file/upload.

class FileControllerTest extends TestCase
{
    use \Illuminate\Foundation\Testing\DatabaseTransactions;

    private $file;

    public function setUp()
    {
        parent::setUp();

        $this->file = new Symfony\Component\HttpFoundation\File\UploadedFile(
            public_path() . '/examples/example.jpg',
            'example.jpg',
            'image/jpeg',
            filesize(public_path() . '/examples/example.jpg'),
            null,
            true // for $test
        );
    }

    /** @test */
    public function it_uploads_a_valid_file()
    {
        var_dump($this->file); // $test = true
        $this->call('POST', 'file/upload', [], …
Run Code Online (Sandbox Code Playgroud)

phpunit file-upload laravel laravel-5 laravel-5.2

22
推荐指数
1
解决办法
3816
查看次数

在PhpUnit测试中匹配JsonStructure - Laravel 5.4

我正在创建一个单元测试,并希望测试JSON响应中返回的结构.我知道它TestResponse提供了一种assertJsonStructure匹配JSON响应结构的方法.但由于某种原因,我无法将其映射$structure到我的响应,结果测试失败.让我分享一下所需的片段.

终点响应

{
   "status": true,
   "message": "",
   "data": [
       {
          "id": 2,
          "name": "Shanelle Goodwin",
          "email": "chaz43@example.net",
          "created_at": "2017-03-05 16:12:49",
          "updated_at": "2017-03-05 16:12:49",
          "user_id": 1
       }
    ]
}
Run Code Online (Sandbox Code Playgroud)

测试功能

public function testEndpoint(){

  $response = $this->get('/api/manufacturer/read', [], $this->headers);
  $response->assertStatus(200);
  $response->assertJsonStructure([
    'status',
    'message',
    'data' => [
      {
        'id',
        'name',
        'email',
        'created_at',
        'updated_at',
        'user_id'
      }
    ]
  ]);
  var_dump("'/api/manufacturer/read' => Test Endpoint");
}
Run Code Online (Sandbox Code Playgroud)

data数组中可以有多个节点,这就是为什么我试图在结构中提到数组,但似乎它没有正确映射.任何帮助将不胜感激:-)

phpunit unit-testing laravel laravel-5 laravel-5.4

22
推荐指数
1
解决办法
5980
查看次数

PHPUnit Selenium,clickAndWait()函数在Opera中不起作用

PHPUnit_Selenium在Opera中遇到问题.如果我在测试代码中单击了元素,则不会加载页面.在其他浏览器中,如Firefox,IE,Chrome和Safari,它可以正常工作.

码:

$browser->clickAndWait(link);
Run Code Online (Sandbox Code Playgroud)

它是SELENIUM REMOTE CONTROL的下一步:

click(link)
waitForPageToLoad(120000)
Run Code Online (Sandbox Code Playgroud)

超时后,如果我点击浏览器中的链接,则重新加载页面.

我有Selenium RC v.2.31.0和Opera版本12.41,但我也测试了Opera 11.50.

你知道什么是错的吗?

php opera selenium phpunit selenium-rc

21
推荐指数
1
解决办法
1462
查看次数

CakePHP单元测试无法识别固定装置

我在使用phpunit v5.1.3的CakePHP v3.x上.我的单元测试似乎没有认识到我的灯具的存在.看来测试是从local(default)数据库连接读取的.

这是我的TestCase类:

namespace App\Test\TestCase\Model\Table;

use Cake\Datasource\ConnectionManager;
use Cake\I18n\Time;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

/**
 * App\Model\Table\ScreensTable Test Case
 *
 * @property \App\Model\Table\ScreensTable ScreensTable
 */
class ScreensTableTest extends TestCase
{
    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'app.screens'
    ];

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $config = TableRegistry::exists('Screens') ? [] : ['className' => 'App\Model\Table\ScreensTable'];
        $this->Screens = TableRegistry::get('Screens', $config);
    }

    public testSomethingHere(){
         $newScreen = $this->Screens->newEntity(['who' => …
Run Code Online (Sandbox Code Playgroud)

phpunit unit-testing cakephp cakephp-3.0

21
推荐指数
1
解决办法
915
查看次数