phpunit mock方法使用不同的参数进行多次调用

时间:2011-05-13 07:25:28

标签: php mocking phpunit

有没有办法为不同的输入参数定义不同的mock-expect?例如,我有一个名为DB的数据库层类。此类具有名为“Query(string $ query)”的方法,该方法在输入时采用SQL查询字符串。我可以为此类(DB)创建模拟,并为依赖于输入查询字符串的不同Query方法调用设置不同的返回值吗?

5 个答案:

答案 0 :(得分:142)

如果可以避免使用at(),那就不合理了,因为as their docs claim

  

at()匹配器的$ index参数是指在给定模拟对象的所有方法调用中从零开始的索引。使用此匹配器时要小心,因为它可能导致脆弱的测试,这些测试与特定的实现细节过于紧密相关。

从4.1开始,您可以使用withConsecutive例如

$mock->expects($this->exactly(2))
     ->method('set')
     ->withConsecutive(
         [$this->equalTo('foo'), $this->greaterThan(0)],
         [$this->equalTo('bar'), $this->greaterThan(0)]
       );

如果你想让它在连续的电话中返回:

  $mock->method('set')
         ->withConsecutive([$argA1, $argA2], [$argB1], [$argC1, $argC2])
         ->willReturnOnConsecutiveCalls($retValueA, $retValueB, $retValueC);

答案 1 :(得分:116)

PHPUnit Mocking库(默认情况下)确定期望是否仅基于传递给expects参数的匹配器和传递给method的约束匹配。因此,只传递给expect的参数的两个with调用将失败,因为两者都匹配,但只有一个将验证具有预期的行为。请参阅实际工作示例后的复制案例。


对于您的问题,您需要使用another question on the subject中列出的->at() ->will($this->returnCallback(

实施例

<?php

class DB {
    public function Query($sSql) {
        return "";
    }
}

class fooTest extends PHPUnit_Framework_TestCase {


    public function testMock() {

        $mock = $this->getMock('DB', array('Query'));

        $mock
            ->expects($this->exactly(2))
            ->method('Query')
            ->with($this->logicalOr(
                 $this->equalTo('select * from roles'),
                 $this->equalTo('select * from users')
             ))
            ->will($this->returnCallback(array($this, 'myCallback')));

        var_dump($mock->Query("select * from users"));
        var_dump($mock->Query("select * from roles"));
    }

    public function myCallback($foo) {
        return "Called back: $foo";
    }
}

转载:

phpunit foo.php
PHPUnit 3.5.13 by Sebastian Bergmann.

string(32) "Called back: select * from users"
string(32) "Called back: select * from roles"
.

Time: 0 seconds, Memory: 4.25Mb

OK (1 test, 1 assertion)


重现为什么两个 - &gt; with()调用dont'work:

<?php

class DB {
    public function Query($sSql) {
        return "";
    }
}

class fooTest extends PHPUnit_Framework_TestCase {


    public function testMock() {

        $mock = $this->getMock('DB', array('Query'));
        $mock
            ->expects($this->once())
            ->method('Query')
            ->with($this->equalTo('select * from users'))
            ->will($this->returnValue(array('fred', 'wilma', 'barney')));

        $mock
            ->expects($this->once())
            ->method('Query')
            ->with($this->equalTo('select * from roles'))
            ->will($this->returnValue(array('admin', 'user')));

        var_dump($mock->Query("select * from users"));
        var_dump($mock->Query("select * from roles"));
    }

}

结果

 phpunit foo.php
PHPUnit 3.5.13 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 4.25Mb

There was 1 failure:

1) fooTest::testMock
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-select * from roles
+select * from users

/home/.../foo.php:27

FAILURES!
Tests: 1, Assertions: 0, Failures: 1

答案 2 :(得分:11)

根据我的发现,解决此问题的最佳方法是使用PHPUnit的价值图功能。

来自PHPUnit's documentation的示例:

class SomeClass {
    public function doSomething() {}   
}

class StubTest extends \PHPUnit_Framework_TestCase {
    public function testReturnValueMapStub() {

        $mock = $this->getMock('SomeClass');

        // Create a map of arguments to return values.
        $map = array(
          array('a', 'b', 'd'),
          array('e', 'f', 'h')
        );  

        // Configure the mock.
        $mock->expects($this->any())
             ->method('doSomething')
             ->will($this->returnValueMap($map));

        // $mock->doSomething() returns different values depending on
        // the provided arguments.
        $this->assertEquals('d', $stub->doSomething('a', 'b'));
        $this->assertEquals('h', $stub->doSomething('e', 'f'));
    }
}

此测试通过。如你所见:

  • 当使用参数“a”和“b”调用函数时,返回“d”
  • 当使用参数“e”和“f”调用函数时,返回“h”

据我所知,这个功能是在 PHPUnit 3.6 中引入的,所以它已经“老”了,它可以安全地用于几乎任何开发或登台环境以及任何持续集成工具

答案 3 :(得分:3)

似乎Mockery(https://github.com/padraic/mockery)支持这一点。在我的情况下,我想检查在数据库上创建了2个索引:

Mockery,作品:

use Mockery as m;

//...

$coll = m::mock(MongoCollection::class);
$db = m::mock(MongoDB::class);

$db->shouldReceive('selectCollection')->withAnyArgs()->times(1)->andReturn($coll);
$coll->shouldReceive('createIndex')->times(1)->with(['foo' => true]);
$coll->shouldReceive('createIndex')->times(1)->with(['bar' => true], ['unique' => true]);

new MyCollection($db);

PHPUnit,这失败了:

$coll = $this->getMockBuilder(MongoCollection::class)->disableOriginalConstructor()->getMock();
$db  = $this->getMockBuilder(MongoDB::class)->disableOriginalConstructor()->getMock();

$db->expects($this->once())->method('selectCollection')->with($this->anything())->willReturn($coll);
$coll->expects($this->atLeastOnce())->method('createIndex')->with(['foo' => true]);
$coll->expects($this->atLeastOnce())->method('createIndex')->with(['bar' => true], ['unique' => true]);

new MyCollection($db);

Mockery也有更好的语法恕我直言。它似乎比PHPUnits内置的模拟功能慢一点,但是YMMV。

答案 4 :(得分:0)

简介

好的,我看到为Mockery提供了一个解决方案,因此我不喜欢Mockery,我会给你一个预言替代方案,但我会先建议你read about the difference between Mockery and Prophecy first.

长话短说:&#34; Prophecy使用名为邮件绑定的方法 - 这意味着该方法的行为不会随着时间的推移而改变,而是通过以下方式改变:另一种方法。&#34;

要覆盖的真实世界有问题的代码

class Processor
{
    /**
     * @var MutatorResolver
     */
    private $mutatorResolver;

    /**
     * @var ChunksStorage
     */
    private $chunksStorage;

    /**
     * @param MutatorResolver $mutatorResolver
     * @param ChunksStorage   $chunksStorage
     */
    public function __construct(MutatorResolver $mutatorResolver, ChunksStorage $chunksStorage)
    {
        $this->mutatorResolver = $mutatorResolver;
        $this->chunksStorage   = $chunksStorage;
    }

    /**
     * @param Chunk $chunk
     *
     * @return bool
     */
    public function process(Chunk $chunk): bool
    {
        $mutator = $this->mutatorResolver->resolve($chunk);

        try {
            $chunk->processingInProgress();
            $this->chunksStorage->updateChunk($chunk);

            $mutator->mutate($chunk);

            $chunk->processingAccepted();
            $this->chunksStorage->updateChunk($chunk);
        }
        catch (UnableToMutateChunkException $exception) {
            $chunk->processingRejected();
            $this->chunksStorage->updateChunk($chunk);

            // Log the exception, maybe together with Chunk insert them into PostProcessing Queue
        }

        return false;
    }
}

PhpUnit Prophecy解决方案

class ProcessorTest extends ChunkTestCase
{
    /**
     * @var Processor
     */
    private $processor;

    /**
     * @var MutatorResolver|ObjectProphecy
     */
    private $mutatorResolverProphecy;

    /**
     * @var ChunksStorage|ObjectProphecy
     */
    private $chunkStorage;

    public function setUp()
    {
        $this->mutatorResolverProphecy = $this->prophesize(MutatorResolver::class);
        $this->chunkStorage            = $this->prophesize(ChunksStorage::class);

        $this->processor = new Processor(
            $this->mutatorResolverProphecy->reveal(),
            $this->chunkStorage->reveal()
        );
    }

    public function testProcessShouldPersistChunkInCorrectStatusBeforeAndAfterTheMutateOperation()
    {
        $self = $this;

        // Chunk is always passed with ACK_BY_QUEUE status to process()
        $chunk = $this->createChunk();
        $chunk->ackByQueue();

        $campaignMutatorMock = $self->prophesize(CampaignMutator::class);
        $campaignMutatorMock
            ->mutate($chunk)
            ->shouldBeCalled();

        $this->mutatorResolverProphecy
            ->resolve($chunk)
            ->shouldBeCalled()
            ->willReturn($campaignMutatorMock->reveal());

        $this->chunkStorage
            ->updateChunk($chunk)
            ->shouldBeCalled()
            ->will(
                function($args) use ($self) {
                    $chunk = $args[0];
                    $self->assertTrue($chunk->status() === Chunk::STATUS_PROCESSING_IN_PROGRESS);

                    $self->chunkStorage
                        ->updateChunk($chunk)
                        ->shouldBeCalled()
                        ->will(
                            function($args) use ($self) {
                                $chunk = $args[0];
                                $self->assertTrue($chunk->status() === Chunk::STATUS_PROCESSING_UPLOAD_ACCEPTED);

                                return true;
                            }
                        );

                    return true;
                }
            );

        $this->processor->process($chunk);
    }
}

摘要

再一次,预言更加棒极了!我的诀窍是利用Prophecy的消息绑定特性,即使它看起来像一个典型的回调javascript地狱代码,从 $ self = $ this; 开始,因为你很少需要编写单元测试像这样我认为这是一个很好的解决方案,它非常容易理解,因为它实际上描述了程序的执行。

BTW:还有第二种选择,但需要更改我们正在测试的代码。我们可以将麻烦制造者包装起来并将它们移到一个单独的类中:

$chunk->processingInProgress();
$this->chunksStorage->updateChunk($chunk);

可以包装为:

$processorChunkStorage->persistChunkToInProgress($chunk);

那就是它,但由于我不想为它创建另一个类,我更喜欢第一个类。