首页 \ 问答 \ PHPUnit如何获取类属性?(PHPUnit how to get a class property?)

PHPUnit如何获取类属性?(PHPUnit how to get a class property?)

为了测试API调用,我想测试一个实体生命周期。

  • 没有内容
  • 发布内容,返回ID
  • 修补内容
  • 获取内容
  • 删除内容

我会使用post方法返回的ID。 我在我的测试类中尝试使用私有属性,但在每个方法测试中,属性都被重置。 我如何在测试类中使用动态变量进行测试?

我的代码示例和PHPUnit的响应:

class CommentControllerTest extends PHPUnit_Framework_TestCase
{
    private $commentId;

    public function setUp()
    {
    }

    public function testPostValidComment()
    {
        $this->commentId = 42;
    }

    public function testUpdateComment()
    {
        var_dump($this->commentId); // NULL
    }

    public function testDeleteComment()
    {
        var_dump($this->commentId); // NULL
    }
}

为什么我的var_dump($this->commentId); 返回NULL


To test an API calling, I would like to test an entity lifecycle.

  • Get with no content
  • Post a content, returning an ID
  • Patch the content
  • Get with content
  • Delete the content

I would use the ID returned in the post method. I try with a private property in my test class but in each method test, the property is reseted. How I can to test with a dynamic variable in my test class?

An example of my code and the response from PHPUnit:

class CommentControllerTest extends PHPUnit_Framework_TestCase
{
    private $commentId;

    public function setUp()
    {
    }

    public function testPostValidComment()
    {
        $this->commentId = 42;
    }

    public function testUpdateComment()
    {
        var_dump($this->commentId); // NULL
    }

    public function testDeleteComment()
    {
        var_dump($this->commentId); // NULL
    }
}

Why my var_dump($this->commentId); returns NULL?


原文:https://stackoverflow.com/questions/24514312
更新时间:2020-10-17 16:10

最满意答案

使用@depends批注建立执行顺序并将值从一个测试传递到下一个测试:

class CommentControllerTest extends PHPUnit_Framework_TestCase
{  
    public function testPostValidComment()
    {
        $commentId = 42;
        return $commentId;
    }

    /**
     * @depends testPostValidComment
     */
    public function testUpdateComment($commentId)
    {
        return $commentId;
    }

    /**
     * @depends testUpdateComment
     */
    public function testDeleteComment($commentId)
    {

    }
}

注意:

如果测试失败,则依赖于它的其他测试将不会运行。 所以使用示例设置:

test POST - > test UPDATE - > test DELETE

如果UPDATE失败,您将不知道DELETE是否有效。

要解决这个问题,您可以将依赖链更改为:

测试POST - >测试UPDATE测试POST - >测试DELETE

因此,如果UPDATE失败,将测试DELETE。 在这种情况下,POST测试将执行两次,一次用于UPDATE,再次用于DELETE。

关于依赖关系的PHPUnit文档


Use the @depends annotation for establishing the execution order and passing the value from one test to the next:

class CommentControllerTest extends PHPUnit_Framework_TestCase
{  
    public function testPostValidComment()
    {
        $commentId = 42;
        return $commentId;
    }

    /**
     * @depends testPostValidComment
     */
    public function testUpdateComment($commentId)
    {
        return $commentId;
    }

    /**
     * @depends testUpdateComment
     */
    public function testDeleteComment($commentId)
    {

    }
}

Note:

if a test fails, other tests that depends on it will not run. So with the example setup:

test POST -> test UPDATE -> test DELETE

if the UPDATE fails you won't know if the DELETE works or not.

To solve this you can change the depends chain to be like this:

test POST -> test UPDATE test POST -> test DELETE

So if the UPDATE fails, the DELETE will be tested. In this case, the POST test will be executed twice, once for the UPDATE and again for the DELETE.

PHPUnit docs on dependencies.

2014-07-04

相关问答

更多

Laravel 5.1 - phpunit - ErrorException:Undefined属性:ExampleTest :: $ baseUrl(Laravel 5.1 - phpunit - ErrorException: Undefined property: ExampleTest::$baseUrl)

从@tk获得信息。 您所要做的就是在父类TestCase中添加受保护的属性 protected $baseUrl = 'http://yoursite.dev'; 它解决了这个问题 Got the info from @tk. All you have to do is add a protected property in the parent class TestCase protected $baseUrl = 'http://yoursite.dev'; It solved the i ...

如何使一个类属性?(How to make a class property?)

以下是我将如何做: class ClassPropertyDescriptor(object): def __init__(self, fget, fset=None): self.fget = fget self.fset = fset def __get__(self, obj, klass=None): if klass is None: klass = type(obj) retur ...

PHPUnit测试一个返回objects属性的方法(PHPUnit test a method that returns an objects property)

答案是“你没有”。 单元测试应该单独测试每个类,你要做的是没有单元测试。 正如我在评论中所说的那样,你违反了德米特定律 ,简单地说 每个单位应该对其他单位的知识有限:只有与当前单位“密切”相关的单位。 每个单位只应与其朋友交谈; 不要和陌生人说话。 只与你的直接朋友交谈。 你有紧密耦合的类需要重新分解。 我先在这里编写了类来说明这一点,但我通常先编写测试。 让我们从链的末端开始: - class there3 { private $id public function setId ...

PHP无法获取类属性(PHP unable to get class property)

更改: $this->name = $attr; 至: $this->name = $value; 因为根据你的开关案例,$ attr被设置为“name”,我认为$ value正在保持你真正需要的东西。 同样的事情将适用于其他交换机案例。 Change: $this->name = $attr; to: $this->name = $value; as $attr IS set to "name" according to your switch case, and I assume th ...

PHPUnit与Symfony服务(PHPUnit with Symfony Service)

您可以(除其他外)创建一个模拟数据库连接并将其放在您的实际连接的位置。 在这个模拟中,您将检查发送到数据库的查询是否是它们应该是的。 You could (among other things) create a mock database connection and put it on place of your actual connection. In this mock you would check if the queries sent to database are what th ...

PHPUnit模拟对象,与SUT的类型相同,是SUT的属性(PHPUnit mocking object that is the same type as the SUT and is a property of the SUT)

该问题与父子关系无关。 您应该定义要模拟的方法: $parent = $this->getMockBuilder(TestClass::class) ->setMethods(['setLocks', 'getLocks']) ->disableOriginalConstructor() ->getMock(); 未经嘲笑的方法将定期调用,您的期望将被忽略。 您可能正在使用PHPUnit 4,因为在PHPUnit 5中,您会在警告中看到您定 ...

按名称获取类属性(Getting class property by name)

我现在唯一能想到的是使用存储库模式编写自定义验证方法。 首先,创建一个所有实体都将实现的接口 public interface IEntity { public string Title {get; set; } } 然后创建存储库: public class Repository<TEntity> where TEntity: class, IEntity { private YourContext context = new YourContext(); privat ...

PHPUnit如何获取类属性?(PHPUnit how to get a class property?)

使用@depends批注建立执行顺序并将值从一个测试传递到下一个测试: class CommentControllerTest extends PHPUnit_Framework_TestCase { public function testPostValidComment() { $commentId = 42; return $commentId; } /** * @depends testPostValidCom ...

相关文章

更多

最新问答

更多
  • Haml + ActionMailer - Rails?(Haml + ActionMailer - Rails?)
  • 将数据从div标签传递到javascript函数[关闭](Pass data from div tags to javascript function [closed])
  • 如何使用imaplib创建电子邮件并将其发送到特定邮箱(How to create an email and send it to specific mailbox with imaplib)
  • Ruby - 使用`require`命令(Ruby - working with `require` command)
  • 用ng值检索时,在md-input-container中隐藏输入文本字段的值(label hiding input text field value in md-input-container when retrieving with ng-value)
  • 以编程方式将字符串宽度值插入sprintf()(Programmatically insert string width value into sprintf())
  • Matplotlib计算给定字符串的轴坐标范围(Matplotlib Calculate Axis Coordinate Extents Given String)
  • 在同一个流连接上返回多个结果以实现HTML5 Server Sent Events(Returning multiple results on the same stream connection to implement HTML5 Server Sent Events)
  • 限制对特定URL的访问(Apache Tomcat)(Restrict access to specific URL (Apache Tomcat))
  • R中的时间序列与ggplot2(Time Series in R with ggplot2)
  • 自动URL参数编码失败(Automatic URL Parameter Encoding Failing)
  • 是否有任何关于JRuby + Clojure集成的开源示例?(Are there any good open source examples of JRuby + Clojure integration?)
  • ActiveX被认为是旧的/过时的标准吗?(Is ActiveX considered old/outdated by todays standards?)
  • SQL Server中的XML查询(XML Query within SQL Server)
  • PL / SQL:在更新尝试时,删除导致unique_violation异常的行(PL/SQL: on update attempt, delete row which causes unique_violation exception)
  • webpack css-loader localIdent名称哈希长度(webpack css-loader localIdent name hash length)
  • 基诺数解析器(Keno number parser)
  • R:索引数据框列的名称范围(R: Index data frame columns by ranges of their names)
  • 限制ASP .net和Javascript中的多个事件(Restrict multiple events in ASP .net & Javascript)
  • 更改行时SQL查询不更新表(SQL query not updating table when row is changed)
  • JavaScript,document.getElementById不从窗体中抓取?(JavaScript, document.getElementById not grabbing from form?)
  • h2数据库上的Mybatis无法插入数据(Mybatis on h2 database can't insert data)
  • KeyboardWillHideNotification未在iOS 9中触发(KeyboardWillHideNotification not firing in iOS 9)
  • jQuery UI Droppable - 如何实际更改HTML?(jQuery UI Droppable - How to actually change the HTML?)
  • 无法将APK安装到root设备中(Can't install APK into rooted device)
  • 在滚动浏览器时,使jQuery UI对话框不改变它的位置(相对于浏览器)(make jQuery UI dialog not change it's position (relative to the browser) when scrolling browser)
  • 我们可以在NativeScript中使用nedb吗?(Can we use nedb with NativeScript?)
  • 使用CancellationToken的竞争条件,其中CancellationTokenSource仅在主线程上被取消(Race condition with CancellationToken where CancellationTokenSource is only cancelled on the main thread)
  • 使用Framework7从JS更新HTML视图中的数据(Update data in HTML view from JS using Framework7)
  • sql server:选择一个外键为NULL的字段(sql server: select a NULL field that is foreign key)