国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What is simulation?
Settings
Create unit tests
Advanced Usage
Conclusion
FAQs about Mockery and Test Dependencies (FAQ)
What is Mockery and why is it important in PHP testing?
How to install and set up Mockery in my PHP project?
How to create mock objects using Mockery?
How to define expectations in Mockery?
What is the difference between simulation and stub in Mockery?
How to use Mockery to test private methods?
How to handle constructor parameters in Mockery?
How to use Mockery to simulate static methods?
How to verify that all expectations are met in Mockery?
How to handle exceptions in Mockery?
Home Backend Development PHP Tutorial Mock your Test Dependencies with Mockery

Mock your Test Dependencies with Mockery

Feb 20, 2025 am 09:07 AM

Mock your Test Dependencies with Mockery

While not everyone is doing this, testing your application is one of the most basic parts of being a developer. Unit testing is the most common test. With unit testing, you can check if a class is running exactly as you expected. Sometimes, you are using third-party services in your application, and it's hard to set up everything for unit testing. This is when the simulation comes into play.

Key Points

  • Mocking is the process of creating a substitute for real objects in a unit test, which is especially useful when testing applications that rely heavily on dependency injection.
  • Mockery is a library created by Pádraic Brady that can be used to mock objects in unit tests, providing an alternative to PHPUnit's default mocking capabilities.
  • Mockery allows developers to define expectations for the number of method calls, parameters to be received, and values ??to be returned, making it a powerful tool for isolating dependencies in unit tests.
  • While PHPUnit can already mock objects, Mockery provides greater flexibility and convenience for developers who want to ensure that their unit tests are not affected by other classes.

What is simulation?

Mocking an object is nothing more than creating a substitute object that replaces the real object in unit tests. If your application is heavily dependent on dependency injection, mocking is a viable way.

There may be several reasons for mocking objects:

  1. It is best to isolate the class when performing unit tests. You don't want another class or service to interfere with your unit tests.
  2. The object does not exist yet. You can create the test first and then build the final object.
  3. Mock objects are usually faster than preparing the entire database for testing.

You may be using PHPUnit when running unit tests. PHPUnit comes with some default simulation features as shown in the documentation. You can read more about simulations and the simulation capabilities of PHPUnit in this article written by Jeune Asuncion.

In this article, we will dive into the library Mockery created by Pádraic Brady. We will create a temperature class that will inject weather services that do not currently exist.

Settings

Let's start by setting up the project. We start with the composer.json file that contains the following content. This will ensure we have mockery and PHPUnit.

<code>{
    "name": "sitepoint/weather",
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.3.3"
    },
    "autoload": {
        "psr-0": { "": "src/" }
    },
    "require-dev": {
        "phpunit/phpunit": "4.1.*",
        "mockery/mockery": "0.9.*"
    }
}</code>

We also create a PHPUnit configuration file called phpunit.xml

<phpunit>
    <testsuite name="SitePoint Weather">
        <directory>./tests</directory>
    </testsuite>
    <listeners>
        <listener class="\Mockery\Adapter\Phpunit\TestListener"
                  file="vendor/mockery/mockery/library/Mockery/Adapter/Phpunit/TestListener.php"/>
    </listeners>
</phpunit>

It is important to define this listener. If there is no listener, if the methods once(), twice() and times() are used incorrectly, no error will be raised. This will be described in detail later.

I also created 2 directories. The src directory is used to hold my classes, and the tests directory is used to store our tests. In the src directory, I created the path SitePointWeather.

We first create the WeatherServiceInterface. Weather services that do not exist will implement this interface. In this case we only provide one method which will give us the temperature of Celsius.

<code>{
    "name": "sitepoint/weather",
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.3.3"
    },
    "autoload": {
        "psr-0": { "": "src/" }
    },
    "require-dev": {
        "phpunit/phpunit": "4.1.*",
        "mockery/mockery": "0.9.*"
    }
}</code>

Therefore, we have a service that provides us with Celsius temperature. I want to get Fahrenheit. To do this, I created a new class called TemperatureService. This service will inject weather services. In addition to this, we also define a method that converts Celsius to Fahrenheit.

<phpunit>
    <testsuite name="SitePoint Weather">
        <directory>./tests</directory>
    </testsuite>
    <listeners>
        <listener class="\Mockery\Adapter\Phpunit\TestListener"
                  file="vendor/mockery/mockery/library/Mockery/Adapter/Phpunit/TestListener.php"/>
    </listeners>
</phpunit>

Create unit tests

We are ready to set up unit tests. We create a TemperatureServiceTest class in the tests directory. In this class we create the method testGetTempFahrenheit() which will test our Fahrenheit method.

The first step to do in this method is to create a new TemperatureService object. Just as we do this, our constructor will request an object that implements the WeatherServiceInterface. Since we don't have such an object yet (we don't want it either), we will use Mockery to create a mock object for us. Let's see what the method looks like after completion.

namespace SitePoint\Weather;

interface WeatherServiceInterface
{
    /**
     * 返回攝氏溫度
     *
     * @return float
     */
    public function getTempCelsius();
}

We first create the mock object. We tell Mockery which object (or interface) we want to mock. The second step is to describe the method that will be called on this mock object. In the shouldReceive() method, we define the name of the method to be called.

We define the number of times this method will be called. We can use once(), twice() and times(X). In this case, we expect it to be called only once. If not called or excessive calls are called, the unit test will fail.

Finally, we define the value to be returned in the andReturn() method. In this case, we return 25. Mockery also has return methods such as andReturnNull(), andReturnSelf() and andReturnUndefined(). If that's what you expect, Mockery can throw exceptions as well.

We now have mock objects that can create our TemperatureService object and test it as usual. 25 degrees Celsius is 77 degrees Fahrenheit, so we check if we receive 77 from our getTempFahrenheit() method.

If you run vendor/bin/phpunit tests/ in your root directory, you will get a green light from PHPUnit, indicating that everything is perfect.

Advanced Usage

The above example is quite simple. No parameters, just a simple call. Let's make things more complicated.

Suppose our weather service also has a way to get the temperature at the exact hours. We add the following method to our current WeatherServiceInterface.

namespace SitePoint\Weather;

class TemperatureService
{
    /**
     * @var WeatherServiceInterace $weatherService 保存天氣服務
     */
    private $weatherService;

    /**
     * 構造函數(shù)。
     *
     * @param WeatherServiceInterface $weatherService
     */
    public function __construct(WeatherServiceInterface $weatherService) {
        $this->weatherService = $weatherService;
    }

    /**
     * 獲取當前華氏溫度
     *
     * @return float
     */
    public function getTempFahrenheit() {
        return ($this->weatherService->getTempCelsius() * 1.8000) + 32;
    }
}

We want to know what the average temperature is between 0:00 and 6:00 pm. To do this, we create a new method in TemperatureService to calculate the average temperature. To do this, we retrieve 7 temperatures from WeatherService and calculate the average.

<code>{
    "name": "sitepoint/weather",
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.3.3"
    },
    "autoload": {
        "psr-0": { "": "src/" }
    },
    "require-dev": {
        "phpunit/phpunit": "4.1.*",
        "mockery/mockery": "0.9.*"
    }
}</code>

Let's take a look at our testing method.

<phpunit>
    <testsuite name="SitePoint Weather">
        <directory>./tests</directory>
    </testsuite>
    <listeners>
        <listener class="\Mockery\Adapter\Phpunit\TestListener"
                  file="vendor/mockery/mockery/library/Mockery/Adapter/Phpunit/TestListener.php"/>
    </listeners>
</phpunit>

We simulate the interface again and define the method to be called. Next, we define the number of times this method will be called. We used once() in the previous example, and now we use times(7) to indicate that we expect this method to be called 7 times. If the method is not called exactly 7 times, the test will fail. If you do not define the listener in the phpunit.xml configuration file, you will not receive notifications about this.

Next, we define the with() method. In the with method, you can define the parameters you expect. In this case, we expect 7 different hours.

Finally, we have the andReturn() method. In this case, we indicate 7 return values. If you define a fewer return values, the last available return value will be repeated each time.

Of course, Mockery can do more. For the complete guide and documentation, I recommend you check out the Github page.

If you are interested in the code of the project above, you can check out this Github page.

Conclusion

Using PHPUnit, you can already mock objects. However, you can also use Mockery as explained in the example above. If you are unit testing your class and you don't want any other class to affect your tests, mockery can help you easily. If you really want to do functional testing, it's better to see if you can integrate real testing. Are you currently using PHPUnit simulation and considering switching to Mockery? Do you want to see more and bigger Mockery examples in subsequent posts? Please let me know in the comments below.

FAQs about Mockery and Test Dependencies (FAQ)

What is Mockery and why is it important in PHP testing?

Mockery is a powerful and flexible PHP mock object framework for unit testing. It is designed as a direct alternative to PHPUnit's mock object functionality. Mockery allows developers to isolate the tested code and create test stand-ins that simulate the behavior of complex objects. This is crucial in unit testing because it ensures that the code being tested does not depend on any external factors or state.

How to install and set up Mockery in my PHP project?

To install Mockery, you need to have Composer, a PHP dependency manager. You can install Mockery by running the command composer require --dev mockery/mockery. After installation, you can set up Mockery in the test file by calling Mockery::close() in the test teardown method to clean up the mock objects.

How to create mock objects using Mockery?

Creating mock objects in Mockery is simple. You can use the mock() method to create a mock object. For example, $mock = Mockery::mock('MyClass'); will create a mock object for MyClass.

How to define expectations in Mockery?

In Mockery, you define expectations by linking methods to mock objects. For example, $mock->shouldReceive('myMethod')->once()->andReturn('mocked value'); This code tells Mockery that expects "myMethod" to be called once and should return "mocked value".

What is the difference between simulation and stub in Mockery?

In Mockery, a mock is the object on which we can set the desired one, while a stub is a mock object that has a pre-programmed response. When response is the only important thing, stubs are usually used, and when testing the interaction itself, mocks are used.

How to use Mockery to test private methods?

It is not recommended to directly test private methods because it violates the encapsulation principle. However, if you want, you can use the shouldAllowMockingProtectedMethods() method in Mockery to allow the mocked protected and private methods.

How to handle constructor parameters in Mockery?

If the class you want to simulate has constructors with arguments, you can pass them as an array to the mock() method. For example, $mock = Mockery::mock('MyClass', [$arg1, $arg2]); will pass $arg1 and $arg2 to the constructor of MyClass.

How to use Mockery to simulate static methods?

Mockery provides a method to simulate static methods using the alias: prefix. For example, $mock = Mockery::mock('alias:MyClass'); will create a mock object that can be used to set the desired setting of the static method of MyClass.

How to verify that all expectations are met in Mockery?

You can use the Mockery::close() method in the test disassembly method to verify that all expectations have been met. If any expectations are not met, Mockery will throw an exception.

How to handle exceptions in Mockery?

You can use the andThrow() method to set up the mock object to throw an exception. For example, $mock->shouldReceive('myMethod')->andThrow(new Exception); will throw an exception when "myMethod" is called.

The above is the detailed content of Mock your Test Dependencies with Mockery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles