janmarek / mockista

Mockista是一个用于模拟的库,是我写的,因为我发现使用PHPUnit进行模拟很糟糕。

v1.1.0 2015-01-26 04:10 UTC

This package is not auto-updated.

Last update: 2024-09-14 13:31:44 UTC


README

通过composer安装

$ composer require --dev janmarek/mockista

建议创建具有mockista功能的基测试类

<?php
abstract class BaseTestCase extends \PHPUnit_Framework_TestCase
{

	/** @var \Mockista\Registry */
	protected $mockista;

	protected function setUp()
	{
		$this->mockista = new \Mockista\Registry();
	}

	protected function tearDown()
	{
		$this->mockista->assertExpectations();
	}

}

快速开始

基本语法

<?php
class SomeTestCase extends BaseTestCase
{

	private $mock1;

	private $mock2;

	protected function setUp()
	{
		parent::setUp();

		$this->mock1 = $this->mockista->create();
		$this->mock1->expects('method')->andReturn(5);
		$this->mock1->expects('method')->once()->with(1, 2, 3)->andReturn(4);

		// or you can use mock builder with nicer syntax
		$builder = $this->mockista->createBuilder();
		$builder->method()->andReturn(5);
		$builder->method(1, 2, 3)->once->andReturn(4);
		$this->mock2 = $builder->getMock();

		// you can create mock of existing class
		$this->mock3 = $this->mockista->create('ExistingClass', array(
			'abc' => 1,              // you can define return values easily
			'def' => function ($a) {
				return $a * 2;
			}
		));
	}

	public function testMock1()
	{
		$this->assertEquals(5, $this->mock1->method());
		$this->assertEquals(5, $this->mock1->method('abc'));
		$this->assertEquals(4, $this->mock1->method(1, 2, 3));
	}

	public function testMock2()
	{
		$this->assertEquals(5, $this->mock1->method());
		$this->assertEquals(5, $this->mock1->method('abc'));
		$this->assertEquals(4, $this->mock1->method(1, 2, 3));
	}

	public function testMock3()
	{
		$this->assertEquals(1, $this->mock1->abc());
		$this->assertEquals(4, $this->mock1->def(2));
	}

}

参数匹配

参数可以通过值进行匹配

$mock->expects('method')->once()->with(1, 'abc', TRUE)->andReturn(4);
$builder->method(1, 'abc', TRUE)->andReturn(4);

或者你可以使用更智能的参数匹配器

$mock->expects('method')->once()->with(Matchers::isInt(), Matchers::isString(), Matchers::isBool())->andReturn(4);
$builder->method(Matchers::isInt(), Matchers::isString(), Matchers::isBool())->andReturn(4);

可用的匹配器包括

  • Matchers::isBool()
  • Matchers::isNumeric()
  • Matchers::isInt()
  • Matchers::isFloat()
  • Matchers::isString()
  • Matchers::isArray()
  • Matchers::regexp($pattern) - 通过正则表达式检查字符串参数
  • Matchers::callback($callback) - 通过你传递的回调中的自定义逻辑检查参数