


Yii 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/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/194/d8454295409f69752ae1c667ca9e3c2e-0.gif" 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( 'content'=>'comment 1', 'status'=>Comment::STATUS_PENDING, 'createTime'=>time(), 'author'=>'me', 'email'=>[email protected]', 'postId'=>$this->posts['sample1']['id'], ),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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Steps for unit testing interfaces and abstract classes in Java: Create a test class for the interface. Create a mock class to implement the interface methods. Use the Mockito library to mock interface methods and write test methods. Abstract class creates a test class. Create a subclass of an abstract class. Write test methods to test the correctness of abstract classes.

Performance tests evaluate an application's performance under different loads, while unit tests verify the correctness of a single unit of code. Performance testing focuses on measuring response time and throughput, while unit testing focuses on function output and code coverage. Performance tests simulate real-world environments with high load and concurrency, while unit tests run under low load and serial conditions. The goal of performance testing is to identify performance bottlenecks and optimize the application, while the goal of unit testing is to ensure code correctness and robustness.

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

Table-driven testing simplifies test case writing in Go unit testing by defining inputs and expected outputs through tables. The syntax includes: 1. Define a slice containing the test case structure; 2. Loop through the slice and compare the results with the expected output. In the actual case, a table-driven test was performed on the function of converting string to uppercase, and gotest was used to run the test and the passing result was printed.

It is crucial to design effective unit test cases, adhering to the following principles: atomic, concise, repeatable and unambiguous. The steps include: determining the code to be tested, identifying test scenarios, creating assertions, and writing test methods. The practical case demonstrates the creation of test cases for the max() function, emphasizing the importance of specific test scenarios and assertions. By following these principles and steps, you can improve code quality and stability.

Summary: By integrating the PHPUnit unit testing framework and CI/CD pipeline, you can improve PHP code quality and accelerate software delivery. PHPUnit allows the creation of test cases to verify component functionality, and CI/CD tools such as GitLabCI and GitHubActions can automatically run these tests. Example: Validate the authentication controller with test cases to ensure the login functionality works as expected.

How to improve code coverage in PHP unit testing: Use PHPUnit's --coverage-html option to generate a coverage report. Use the setAccessible method to override private methods and properties. Use assertions to override Boolean conditions. Gain additional code coverage insights with code review tools.

In Go function unit testing, there are two main strategies for error handling: 1. Represent the error as a specific value of the error type, which is used to assert the expected value; 2. Use channels to pass errors to the test function, which is suitable for testing concurrent code. In a practical case, the error value strategy is used to ensure that the function returns 0 for negative input.
