标签: phpunit

使用 PHPUnit 中先前测试用例的值

我试图为第一个测试函数内的变量分配一个值,然后在类内的其他测试函数中使用它。

现在在我的代码中,第二个函数由于此错误而失败:

   1) ApiAdTest::testApiAd_postedAdCreated
GuzzleHttp\Exception\ClientException: Client error: 404
Run Code Online (Sandbox Code Playgroud)

我不知道为什么。代码如下所示:

 class ApiAdTest extends PHPUnit_Framework_TestCase
    {
        protected $adId;
        private static $base_url = 'http://10.0.0.38/adserver/src/public/';
        private static $path = 'api/ad/';

        //start of expected flow

        public function testApiAd_postAd()
        {
            $client = new Client(['base_uri' => self::$base_url]);
            $response = $client->post(self::$path, ['form_params' => [
              'name' => 'bellow content - guzzle testing'
              ]]);
            $data = json_decode($response->getBody());
            $this->adId = $data->id;

            $code = $response->getStatusCode();
            $this->assertEquals($code, 200);
        }

        public function testApiAd_postedAdCreated()
        {
            $client = new Client(['base_uri' => self::$base_url]);
            $response = $client->get(self::$path.$this->adId);
            $code …
Run Code Online (Sandbox Code Playgroud)

php phpunit

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

在测试中访问静态类中的私有静态属性

是否可以$measurements在测试用例中访问该属性?

class Performance
{
    private static $measurements = [];

    public static function createMeasurement()
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试了这样的事情:

$reflection = new \ReflectionClass(get_class(Performance));
$property = $reflection->getProperty('measurements');
$property->setAccessible(true);
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为Use of undefined constant Performance - assumed 'Performance'. 如何告诉 php 从静态类中获取对象?

php phpunit

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

模拟获取参数 symfony2 和 phpunit

我想测试它具有的一个控制器:

$deviceGet = strtolower($request->query->get('device'));

我的问题是:如何模拟它以在我的控制器中进行测试?

class SetDeviceListenerTest extends \PHPUnit_Framework_TestCase {


     /**
     * @test
     * @dataProvider deviceGetCases
     */
public function shouldSetRequestDeviceWithDeviceGetOnMasterRequest(
    ?string $device
): void {
    $request = $this->getRequestMock();

    $request->expects($this->once())
        ->method('get')
        ->with('device')
        ->willReturn($device);


    /* @var Request $request */
    $request->server = new ServerBag();
    $request->headers = new HeaderBag();

    $event = $this->getEventMock();
    $event->expects($this->once())
        ->method('isMasterRequest')
        ->willReturn(true);
Run Code Online (Sandbox Code Playgroud)

它返回错误,因为

 $request->expects($this->once())
        ->method('get')
        ->with('device')
        ->willReturn($device);
Run Code Online (Sandbox Code Playgroud)

失败

谢谢你!!

phpunit unit-testing symfony

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

使用 Phpunit 进行功能测试:InvalidArgumentException:无法访问字段

我正在尝试测试表单,但出现无法访问的字段异常。

我的控制器的代码:

class StudentController extends Controller
{
  /**
   * @Route("/student/new",name="create_new_student")
   */
   public function newAction(Request $request){
      $student = new Student();
      $form = $this->createFormBuilder($student)->add('name',TextType::class)
          ->add('save',SubmitType::class,['label' => 'Create student'])->getForm();
      $form->handleRequest($request);
      if($form->isSubmitted()){
           $student = $form->getData();
           $name = $student->getName();
           echo "Your name is ".$name;
           die();       
      }

      return $this->render(':Student:new.html.twig',['form' => $form->createView()]);
   }
}
Run Code Online (Sandbox Code Playgroud)

我的学生控制器测试:

class StudentControllerTest extends WebTestCase
{

  public function testNew(){
    $client = static::createClient();
    $crawler = $client->request('POST','/student/new');
    $form = $crawler->selectButton('Create student')->form();
    $form['name'] = 'Student1';
    $crawler = $client->submit($form);
    $this->assertGreaterThan(0,$crawler->filter('html:contains("Your name is Student1")')->count());
  }
}
Run Code Online (Sandbox Code Playgroud)

当我使用 phpunit …

testing phpunit symfony

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

Symfony 3.4 和 PHPUnit 7.0.1 不可能吗?

是否可以将最新版本的 PHPUnit (7.0.1) 与 Symfony 3.4 一起使用?我收到错误

PHP 致命错误: Symfony\Bridge\PhpUnit\CoverageListener::startTest(PHPUnit\Framework\Test $test) 的声明必须与 PHPUnit\Framework\TestListener::startTest(PHPUnit\Framework\Test $test) 兼容: void in / var/www/vhosts/facto/vendor/symfony/phpunit-bridge/CoverageListener.php 第 30 行

我的 phpunit-bridge 与最新版本的 PHPUnit 不兼容。

phpunit symfony

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

Homebrew:如何安装 PHPUnit 6.5?

我正在尝试安装 php 单元版本 6.5。

我已经安装了 7.0.1,并尝试使用以下命令安装 phpunit 6.5 版本:

brew install phpunit@6.5
Run Code Online (Sandbox Code Playgroud)

Brew 告诉我安装了旧版本,但phpunit --version版本是 7.0.1。

尝试brew switch phpunit 6.5,我收到消息:

Error: phpunit does not have a version "6.5" in the Cellar.
Versions available: 7.0.1
Run Code Online (Sandbox Code Playgroud)

我需要采取哪些步骤才能将版本切换到 6.5?

homebrew phpunit

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

phpunit“未执行任何测试”

我无法通过 PHPUnit 测试解决问题。这是我的代码,它有问题。这是年度百分比率计算(https://en.wikipedia.org/wiki/Annual_percentage_rate)。

\n\n

在命令中:

\n\n
    C:\\Users\\Shambler\\Downloads\\test-taeg-senior\\test-taeg>phpunit\nPHP Warning:  Module \'oci8\' already loaded in Unknown on line 0\n\nWarning: Module \'oci8\' already loaded in Unknown on line 0\nPHPUnit 3.7.21 by Sebastian Bergmann.\n\nConfiguration read from C:\\Users\\Shambler\\Downloads\\test-taeg-senior\\test-taeg\\phpunit.xml\n\n\n\nTime: 74 ms, Memory: 2.00MB\n\nNo tests executed!\n\nC:\\Users\\Shambler\\Downloads\\test-taeg-senior\\test-taeg>\n
Run Code Online (Sandbox Code Playgroud)\n\n

不要考虑 Oracle 模块,那是另一个故事。我在“composer install”之后运行了“phpunit”。

\n\n

项目/测试/test-general.php:

\n\n
    <?php\n\nuse MotorK\\{ Rate, Tae, Taeg };\n\nclass TestTaeg extends \\PHPUnit\\Framework\\TestCase {\n\n    /**\n     * Example from http://www.calcolatoremutui.it/tan-e-taeg/\n     */\n    public function test_tae() {\n        $obj = Tae::init( 5, 12 );\n\n        $this->assertEquals( 5.116, round( $obj->calculate(), 3 …
Run Code Online (Sandbox Code Playgroud)

php phpunit

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

如何为 laravel 项目设置 phpUnit 别名?

我使用 Composer 来安装 phpunit 来进行项目。

composer require --dev phpunit/phpunit ^7
Run Code Online (Sandbox Code Playgroud)

安装正确。但如何设置别名来使用

~$ phpunit
Run Code Online (Sandbox Code Playgroud)

运行所有测试。我发现这~$ vendor/bin/phpunit有效。在 Ubuntu 18.04 中在哪里以及如何设置别名?

phpunit alias ubuntu-18.04

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

如何获取测试的 Doctrine 类元数据?

一位同事想要在测试中模拟实体经理。他有这样的代码:

    ...
    $em = $this->createMock(EntityManager::class);
    $myRepository = new NewslettersStatisticSnapshotRepository(
        $em,
        NewslettersStatisticSnapshot::class
    );

    $em->method('getRepository')->willReturn($myRepository);
    ...
Run Code Online (Sandbox Code Playgroud)

...当我运行他的测试时,我得到了这个:

TypeError:传递给 Doctrine\ORM\EntityRepository::__construct() 的参数 2 必须是 Doctrine\ORM\Mapping\ClassMetadata 的实例,给定字符串

我如何挖掘该类的元数据?

php phpunit doctrine metadata symfony

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

为什么 returnValueMap() 返回 NULL

尝试在测试中模拟学说存储库,当与findOneBy方法一起使用时,returnValueMap() 始终返回 NULL 。

我模拟了两个实体,然后尝试使用给定的返回值映射来模拟它们的存储库。测试失败,调试显示 returnValueMap() 返回 NULL。

这是要测试的类(反规范化器)

<?php

declare(strict_types=1);

namespace App\Serializer;

use App\Entity\AdditionalService;
use App\Repository\AdditionalServiceRepository;
use Dto\AdditionalServiceCollection;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class AdditionalServiceCollectionDenormalizer implements DenormalizerInterface
{
    /** @var AdditionalServiceRepository */
    private $additionalServiceRepository;

    public function __construct(AdditionalServiceRepository $additionalServiceRepository)
    {
        $this->additionalServiceRepository = $additionalServiceRepository;
    }

    public function denormalize($mappedCsvRow, $class, $format = null, array $context = [])
    {
        $addtionalServicesCollection = new AdditionalServiceCollection();
        foreach ($mappedCsvRow as $fieldName => $fieldValue) {
            /** @var AdditionalService $additionalService */
            $additionalService = $this->additionalServiceRepository->findOneBy(['name'=>$fieldName]);

            if ($additionalService) {
                $addtionalServicesCollection->add($additionalService->getId(), $fieldValue);
            }
        } …
Run Code Online (Sandbox Code Playgroud)

phpunit symfony doctrine-orm php-7

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