定制 ernestmarcinko/mockutils 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ernestmarcinko/mockutils

Composer 安装命令:

composer require --dev ernestmarcinko/mockutils

包简介

PHPUnit test mocking utility tools

README 文档

README

tests

This package provides ome utility functions for PHPUnit TestCase class (and descendants) via the MockUtils trait:

  • Global Mocks - setGlobalMocks() & unsetGlobalMocks() methods to set global function mocks within a namespace
  • Exception assertion - via expectCatchException() - Method similar to expectException(), but without terminating the test execution

Installation & Inclusion

To install the package:

composer require ernestmarcinko/mockutils --dev

Including in your tests

There are two ways, one is using a trait to extend your TestCase functionality (recommended):

use ErnestMarcinko\MockUtils\MockUtils;
use PHPUnit\Framework\TestCase;

class MyTest extends TestCase {
	use MockUtils;
	...
}

..or use the MockUtilsTestCase class instead of TestCase:

use ErnestMarcinko\MockUtils\MockUtilsTestCase;

class MyTest extends MockUtilsTestCase {
	...
}

MockUtilsTestCase is only an empty class extending TestCase and using MockUtils.

Global Mocks

The trait adds two utility functions to setGlobalMocks() and unsetGlobalMocks() to set and unset global mocks.

setGlobalMocks

protected function setGlobalMocks(array $global_mocks, ?string $namespace): void

Sets global mocks to the given namespace.

Parameters

Param Type Description Required Extra info
$global_mocks array<string,mixed|callable> Array of global function name and return value or callable true
$namespace string The namespace of the code where the global function should be set false Make sure to use the code namespace, not the test code namespace

Example

Say you have a service, which uses curl_exec to get a response from an API. During testing you want to mock it and avoid actual connection to the API and instead test with pre-defined responses.

namespace MyNamespace\MySubNamespace;

class MyClass {
	public function handler() {
		//....
		
		$response = curl_exec($curl); // you want to mock this
		
		//You do something with $response below
	}
}

In the test we need the curl_exec to return 'response' for the mock, to do that:

namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->setGlobalMocks(
			[
				'curl_exec' => 'response'
			], 
			'MyNamespace\\MySubNamespace'
		)
	
		$o = new MyClass();
		$this->assertSame( 'expected output', $o->handler() );
	}
}

It's also possible to define a callable instead of a static response:

namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->setGlobalMocks(
			[
				'curl_exec' => function($curl) {
					return 'response';
				}
			], 
			'MyNamespace\\MySubNamespace'
		)
	
		$o = new MyClass();
		$this->assertSame( 'expected output', $o->handler() );
	}
}

unsetGlobalMocks

protected function unsetGlobalMocks(?array $global_mocks=null): void

Unsets the given global mocks or all global mocks previously defined.

Parameters

Param Type Description Required Extra info
$global_mocks array<string> Array of global function names false

Examples

namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->setGlobalMocks(
			[
				'time' => fn()=>time()-3600,
				'json_decode' => array(),
				'strval' => fn($v)=>$v,
			], 
			'MyNamespace\\MySubNamespace'
		)
		$o = new MyClass();
		$this->assertSame( 'expected output 1', $o->handler() );
		
		$this->unsetGlobalMocks(array('time')); // unset just the time mock
		$this->assertSame( 'expected output 2', $o->handler() );
		
		$this->unsetGlobalMocks(); // unset all remaining mocks
		$this->assertSame( 'expected output 3', $o->handler() );
	}
}

Exception Assertion

expectCatchException

Checks if the exception was thrown without execution termination.

protected function expectCatchException(callable $fn, string $throwable, ?string $message = null): void 

Compared to PHPUnit core TestCase::expectException this function will not terminate the test execution. The function to test must be however passed in as a closure, ex.: expectCatchException(fn()=>$o->myMethod(), ...)

Parameters

Param Type Description Required Extra info
$fn callable Function to test true Use closure fn()=>{$myObj->myMethod();} to pass in any method
$throwable class-string<Throwable> Expected exception class name true
$message string The expected error message false (optional) If set, then the function will also check the Exception message.

Return values

The function is void, does not return anything, however:

expectCatchException will trigger TestCase::fail() if no exception was thrown, or any of the criteria was not met.

Example

namespace MyTestNamespace;

class TestMyClass {
	public function testHandler() {
		$this->expectCatchException(function(){
			throw new Exception('hey!');
		}, Exception::class);
		
		// Execution continues
		
		$this->expectCatchException(function(){
			throw new Exception('hey!');
		}, Exception::class, 'hey!');
		
		$o = new MyClass();
		$this->expectCatchException(fn()=>$o->handle(), Exception::class);
		
		$this->expectCatchException(
			fn()=>$o->handle(), 
			Exception::class,
			'Exception message!'
		);
	}
}

ernestmarcinko/mockutils 适用场景与选型建议

ernestmarcinko/mockutils 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 141 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 03 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「testing」 「phpunit」 「test」 「mock」 「utlis」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 ernestmarcinko/mockutils 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ernestmarcinko/mockutils 我们能提供哪些服务?
定制开发 / 二次开发

基于 ernestmarcinko/mockutils 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 141
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 7
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-03-27