search
HomeBackend DevelopmentPHP TutorialYii Framework Official Guide Series Supplement 39 - Testing: Unit Testing



Because the Yii testing framework is built on PHPUnit, it is recommended that you read through the PHPUnit documentation before understanding how to write a unit test. Let's briefly summarize the basic principles of writing a unit test in Yii:

  • A unit test is written in the form of the XyzTest class inherited from CTestCase or CDbTestCase, where Xyz represents the test to be Class. For example, if we want to test the Post class, we will name the test class PostTest accordingly. The base class CTestCase is a general unit test class, while CDbTestCase is only suitable for testing AR model classes. Since PHPUnit_Framework_TestCase is the two The parent class of the class, we can inherit all methods from this class.

  • Unit test classes are saved in PHP files in the form of XyzTest.php. For convenience, unit test files are usually saved in the protected/tests/unit folder .

  • The test class mainly contains a series of testAbc methods, where Abc is usually the class method to be tested.

  • The test method usually contains a A series of assertion statements (e.g. assertTrue, assertEquals) serve as breakpoints to verify the behavior of the target class.

Below we mainly explain how to create AR Model class to write unit tests. Our test class will inherit from CDbTestCase because it provides database-specific state support. We have discussed database-specific state in detail in the previous chapter.

Suppose we want to test For the Comment model class in the blog case, you can first create a class named CommentTest, and then save it as protected/tests/unit/CommentTest.php:

class CommentTest extends CDbTestCase
{
    public $fixtures=array(
        'posts'=>'Post',
        'comments'=>'Comment',
    );

    ......
}

in this class , we specify the member variable fixtures as an array containing the specific state (fixtures) to be used for this test. This array represents the mapping from a specific state name to a model class or a specific state table name (e.g. from posts to Post). Note that when mapping to a specific state table name, it should be in the data Table names are prefixed with a colon (e.g. <img class="wp-smiley lazy" src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/194/d8454295409f69752ae1c667ca9e3c2e-0.gif?x-oss-process=image/resize,p_40" alt="Yii Framework Official Guide Series Supplement 39 - Testing: Unit Testing"> ost) to distinguish them from mapping to model classes. When using model class names, the corresponding table will be treated as a specific state table. As we described before, a certain state table will be reset to some known state each time a test method is executed.

Specific state names allow us to access specific state data in a very convenient way in test methods. The following code shows typical usage:

// return all rows in the 'Comment' fixture table
$comments = $this->comments;
// return the row whose alias is 'sample1' in the `Post` fixture table
$post = $this->posts['sample1'];
// return the AR instance representing the 'sample1' fixture data row
$post = $this->posts('sample1');

Note: If a specific status declaration uses its data table name (e.g. 'posts'=>'Yii Framework Official Guide Series Supplement 39 - Testing: Unit Testingost'), then the third usage method above will be invalid because we have already There is no longer any information related to the model class.

Next, we have to write the testApprove method to test the approve method in the Comment model class. The code is very simple and clear: First we Insert a comment to be reviewed; then verify this review comment by retrieving data from the database; finally we call the approve method and pass the review.

public function testApprove()
{
    // insert a comment in pending status
    $comment=new Comment;
    $comment->setAttributes(array(
        &#39;content&#39;=>&#39;comment 1&#39;,
        &#39;status&#39;=>Comment::STATUS_PENDING,
        &#39;createTime&#39;=>time(),
        &#39;author&#39;=>&#39;me&#39;,
        &#39;email&#39;=>[email protected]&#39;,
        &#39;postId&#39;=>$this->posts[&#39;sample1&#39;][&#39;id&#39;],
    ),false);
    $this->assertTrue($comment->save(false));

    // verify the comment is in pending status
    $comment=Comment::model()->findByPk($comment->id);
    $this->assertTrue($comment instanceof Comment);
    $this->assertEquals(Comment::STATUS_PENDING,$comment->status);

    // call approve() and verify the comment is in approved status
    $comment->approve();
    $this->assertEquals(Comment::STATUS_APPROVED,$comment->status);
    $comment=Comment::model()->findByPk($comment->id);
    $this->assertEquals(Comment::STATUS_APPROVED,$comment->status);
}

The above is the content of Yii Framework Official Guide Series Supplement 39 - Testing: Unit Testing. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools