jdgrimes/wp-filesystem-mock

WordPress 文件系统 API 的适配器,用于在 PHPUnit 测试中使用模拟文件系统

0.1.2 2017-09-14 20:28 UTC

This package is auto-updated.

Last update: 2024-09-14 10:33:08 UTC


README

提供可用来模拟文件系统的类,以及使用它的 WordPress 文件系统 API 的适配器。这对于包括简单文件系统操作的单元测试非常有用。

要求

  • PHP: 5.2.17+
  • WordPress: 3.9+

它可能也适用于更早的 WordPress 版本,但我只测试了这些版本。

请注意,WordPress 实际上不是必需的,您可以在没有它的前提下使用文件系统模拟器(只是您将无法使用 WordPress 文件系统 API 的扩展)。

安装

您可以使用 Composer 进行安装

composer require --dev jdgrimes/wp-filesystem-mock

使用方法

如果您没有使用自动加载,您需要首先加载它

		/**
		 * WordPress's base filesystem API class.
		 *
		 * We need to make sure this is loaded before we can load the mock.
		 */
		require_once( ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php' );

		/**
		 * The filesystem API shim that uses mock filesystems.
		 */
		require_once( MY_TESTS_DIR . '/../../vendor/jdgrimes/wp-filesystem-mock/src/wp-filesystem-mock.php' );

		/**
		 * The mock filesystem class.
		 */
		require_once( MY_TESTS_DIR . '/../../vendor/jdgrimes/wp-filesystem-mock/src/wp-mock-filesystem.php' );

要在测试中使用模拟文件系统,只需添加以下代码(例如,在您的 PHPUnit 测试用例的 setUp() 方法中)

		// Creating a new mock filesystem.
		// We assign it to a member property so we can access it later.
		$this->mock_fs = new WP_Mock_Filesystem;
		
		// Create the /wp-content directory.
		// This part is optional, and you'll do more or less setup here depending on
		// what you are testing.
		$this->mock_fs->mkdir_p( WP_CONTENT_DIR );

		// Tell the WordPress filesystem API shim to use this mock filesystem.
		WP_Filesystem_Mock::set_mock( $this->mock_fs );
		
		// Tell the shim to start overriding whatever other filesystem access method
		// is in use.
		WP_Filesystem_Mock::start();
	
		// Set up the $wp_filesystem global, if the code being tested doesn't do this.
		WP_Filesystem();

要全面了解它的功能,请查看源代码。