PHPUnit Configuration and use tutorial in Windows

Source: Internet
Author: User
Tags add connect variables php code version variable zend visual studio





Because our project involves PHP, we need to unit test the PHP code. After some understanding, decided to use PHPUnit to test PHP. PHPUnit spent a lot of time groping how to configure PHPUnit, Reader Web document is a tear. But know how to configure, in fact, it is very simple.


  • System: Windows 10 Professional Edition

  • PHP Version: PHP 5.5.12

  • Server Tools: Wampserver 2.5

  • PHPUnit Version: PHPUnit 4.8


First, configure PHPUnit



First to PHPUnit official website (click here to enter) download the corresponding version. We are using PHP 5.5, so we choose PHPUnit 4.8. Get.pharthe file and change the name tophpunit.phar.



Put the file in any location. For my own example, I put it in the directory of our project, that isD:\repository\CourseManagement\mobile_api_test.



Right click on my Computer and select properties . Click on the Advanced system settings on the left. Now eject the system Properties , select the Advanced tab, and click on the environment variable in the lower right corner. In the user variable, double-click Path, add the value after the variable ;D:\repository\CourseManagement\mobile_api_test(note the first semicolon, the path fills the Phpunit.phar path). Configure this is to be able to use PHPUnit in any location, do not configure, you need to phpunit.phar the path to use the PHPUnit.


One thing that is not mentioned in the official document is that PHP's environment variables are set. For example, I amphp.exeinE:\software\wamp\bin\php\php5.5.12, then also to add after the PATH ;E:\software\wamp\bin\php\php5.5.12. PS: Probably because I do not have the IDE installed PHP, so I have not configured it, accidentally just think of the possibility to add this environment variable.


Press the shortcut key andWin + Renter CMD and return. Enter the path to store the Phpunit.phar. Enterecho @php "%~dp0phpunit.phar" %* > phpunit.cmdand return. Then enterphpunit --versionand return. If the outputPHPUnit x.y.z by Sebastian Bergmann and contributors.is configured (if wrong, enterexitand return and start over again). The following figure:






Second, the use of phpunit for testing



Using PHPUnit, you must use a class . Take login.php for example (locationD:\repository\CourseManagement\mobile_api), our initial version is this (Welcome to the code in this blog):


<php 
 
    error_reporting(0); 
 
    $workNumber = $_POST["login-user"]; 
    $password = $_POST["login-password"]; 
    $tableName = $_POST["ident"]; 
 
    $con = mysqli_connect("localhost", "root", "", "teacher_class_system"); 
    if (!$con) { 
        die('Could not connect: ' . mysql_error()); 
    } else { 
        mysqli_query($con, "SET NAMES utf8"); 
 
        $result = mysqli_query($con, "SELECT * FROM $tableName where workNumber = $workNumber and password = $password"); 
        if (mysqli_num_rows($result) < 1) { 
                echo "false"; 
        } else { 
                $result_arr = mysqli_fetch_assoc($result); 
                echo json_encode($result_arr, JSON_UNESCAPED_UNICODE); 
        } 
    } 
 
    > 



This is impossible to test, so make a change. Firstlogin.phpCreate a folder in the folder andclassescreate a new one inclass_login.phpit, with thelogin.phpmodified version:


<php
 
    class Login {
        // The test tool PHPUnit requires that the variable default value must be given here, so the default is empty.
        public function login ($ workNumber = "", $ password = "", $ tableName = "") {
            $ con = mysqli_connect ("localhost", "root", "", "teacher_class_system");
            if (! $ con) {
                die ('Could not connect:'. mysqli_error ());
            } else {
                mysqli_query ($ con, "SET NAMES utf8");
 
                $ result = mysqli_query ($ con, "SELECT * FROM $ tableName where workNumber = $ workNumber and password = $ password");
                if (! $ result mysqli_num_rows ($ result) == 0) {
                    return "false";
                } else {
                    $ result_arr = mysqli_fetch_assoc ($ result);
                    return json_encode ($ result_arr, JSON_UNESCAPED_UNICODE);
                }
            }
        }
    }
 
    >



In addition, the original content should also be modifiedlogin.php, as follows:


<php 
  error_reporting(0); 
 
  require_once './classes/class_login.php'; 
 
  $workNumber = $_POST["login-user"]; 
  $password = $_POST["login-password"]; 
  $tableName = $_POST["ident"]; 
 
  $log = new Login; 
  $response = $log->login($workNumber,$password,$tableName); 
 
  if($response != "false") { 
      session_start(); 
      $_SESSION['id']=$tableName; 
  } 
 
  echo $response; 
 
  > 



Start writing test files



I put the test files inD:\repository\CourseManagement\mobile_api_testthis folder. Create a new file ' login_test.php ' and write the following code:


<php
   require_once dirname (__ FILE __). '/ .. / mobile_api / classes / class_login.php';
 
   class LoginTest extends PHPUnit_Framework_TestCase {
       public function testLoginSuccess () {
           $ expected = '{"workNumber": "00001", "password": "00001", "name": "watermelon", "sex": "male", "birthday": "20151201", "department": " Computer "," telephone ":" 110 "," email ":" git@github.com "} ';
 
           $ workNumber = '00001';
           $ password = '00001';
           $ tableName = 'user_teacher';
           $ lg = new Login;
           $ actual = $ lg-> login ($ workNumber, $ password, $ tableName);
 
           $ this-> assertEquals ($ expected, $ actual);
       }
 
       function testLoginFail () {
           $ expected = 'false';
 
           $ workNumber = '11111';
           $ password = '11111';
           $ tableName = 'user_teacher';
 
           $ lg = new Login;
           $ actual = $ lg-> login ($ workNumber, $ password, $ tableName);
           $ this-> assertEquals ($ expected, $ actual);
       }
   }
 
   >


Executing test files



Shortcut key Win + R, input cmd and enter. Enter the directory where the test file is to bephpunit login_test.phpexecuted and run the test.






The simple test is done.



Iii. the process of exploration



First download phpunit, get.pharfiles, think to unpack, embarrassed. Looking for a long time to find that there is a can extract such a file of the site (click here to enter). However, there is no use ...



Follow the official documentation and run with an error:


' PHP ' is not an internal or external command, nor is it a running program
or batch files.


Google search, Bing search, StackOverflow Search, Baidu Search, found that the answer is not used.


Mainly because they all default you have configured the PHP environment variables ...


Finally think about whether the previous generation of thephpunit.cmdproblem? So look at the contents of this file. Suddenly think of the PHP environment variable is not set the reason? Open cmd and enterphp --version. Get:


' PHP ' is not an internal or external command, nor is it a running program
or batch files.


Same as the above error! Sure enough, it's the problem here. So;E:\software\wamp\bin\php\php5.5.12add it to the environment variable. To run it againphp --version


PHP 5.5.12 (cli) (built: Apr 30 2014 11:20:58) 
Copyright (c) 1997-2014 The PHP Group 
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies 
with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans 


Then gophpunit.cmdto the folder where you are runningphpunit --version. Get:


PHPUnit 4.8.18 by Sebastian Bergmann and contributors.


Problem solved!



After this exploration, later encountered "Find XXX" This problem, the first will be reminded of the setting of environment variables.



For example, on the same day in the afternoon, I wanted to use the Git feature of Visual Studio code, but I was prompted:






The first reaction is: I clearly installed the msysgit AH.



The second response is: Will the environment variable not be configured? Open environment variable configuration, sure enough. Thengit.exeadd the path to the folder where you are located. Restart visual Studio Code, problem Resolution!


"Responsible Editor: Wangxueyan TEL: (010) 68476606"


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.