Best Mockery code snippet using CompositeExpectation
UnitSeleniumTestCase.php
Source:UnitSeleniumTestCase.php  
2namespace Sepehr\PHPUnitSelenium\Tests\Unit;3use Mockery;4use Mockery\MockInterface;5use phpmock\mockery\PHPMockery;6use Mockery\CompositeExpectation;7use Sepehr\PHPUnitSelenium\Util\Locator;8use Sepehr\PHPUnitSelenium\Util\Filesystem;9use Sepehr\PHPUnitSelenium\SeleniumTestCase;10use Facebook\WebDriver\Remote\RemoteWebDriver;11use Sepehr\PHPUnitSelenium\WebDriver\WebDriverBy;12use Facebook\WebDriver\Remote\DesiredCapabilities;13use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;14/**15 * Base class for all unit tests that deal with test doubles.16 *17 * This may seem a little bit complicated, and in fact, it is! But in return18 * it provides an easy-to-use API to write unit tests as fast as possible. For19 * example, let's inject a dependency mock into the SUT:20 *21 *     $this->inject($this->spy(RemoteWebDriver::class));22 *23 * Or better:24 *25 *     $this->inject(26 *         $this->mock('overload:' . DesiredCapabilities::class)27 *             ->shouldReceive('create')28 *             ->once()29 *     );30 *31 * Or even better:32 *33 *     $this->inject(WebDriverBy::class)34 *         ->shouldReceive('create')35 *         ->once()36 *         ->withAnyArgs()37 *         ->andReturn(Mockery::slef());38 *39 * How cool is that?!40 */41abstract class UnitSeleniumTestCase extends SeleniumTestCase42{43    use MockeryPHPUnitIntegration;44    /**45     * An array of reusable dependency test doubles.46     *47     * @var MockInterface[]48     */49    protected $doubles = [];50    /**51     * Test setup.52     */53    public function setUp()54    {55        // Mock all calls to sleep() during unit tests56        PHPMockery::mock('Sepehr\PHPUnitSelenium', 'sleep')57            ->zeroOrMoreTimes()58            ->andReturn(0);59        parent::setUp();60    }61    /**62     * Manages test doubles.63     *64     * @param string $doubleId65     * @param \Closure|null $closure66     * @param string $doubleType67     *68     * @return MockInterface69     * @throws \Exception70     */71    protected function double($doubleId, $closure = null, $doubleType = 'mock')72    {73        if (key_exists($doubleId, $this->doubles)) {74            return $closure75                ? $closure($this->doubles[$doubleId])76                : $this->doubles[$doubleId];77        }78        try {79            return $this->doubles[$doubleId] = $closure80                ? Mockery::$doubleType($doubleId, $closure)81                : Mockery::$doubleType($doubleId);82        } catch (\Exception $e) {83            throw new \Exception(84                "Could not find/create a $doubleType with identifier: $doubleId\nMessage: {$e->getMessage()}"85            );86        }87    }88    /**89     * Mock interface.90     *91     * @param string $mockId92     * @param \Closure|null $closure93     *94     * @return MockInterface95     * @throws \Exception96     */97    protected function mock($mockId, $closure = null)98    {99        return $this->double($mockId, $closure, 'mock');100    }101    /**102     * Spy interface.103     *104     * @param string $spyId105     * @param \Closure|null $closure106     *107     * @return MockInterface108     * @throws \Exception109     */110    protected function spy($spyId, $closure = null)111    {112        return $this->double($spyId, $closure, 'spy');113    }114    /**115     * Genius test double injector; she knows how to inject!116     *117     * @param MockInterface|CompositeExpectation|string $double118     * @param string $doubleType119     *120     * @return MockInterface121     */122    protected function inject($double, $doubleType = 'mock')123    {124        $double = $this->normalizeDouble($double, $doubleType);125        $injector = $this->getDependencyInjector($double);126        // Each dependency might have its own logic for127        // injection, so the separate methods...128        return $this->$injector($double);129    }130    /**131     * Injects a mock.132     *133     * @param MockInterface|CompositeExpectation|string $double134     *135     * @return MockInterface136     */137    protected function injectMock($double)138    {139        return $this->inject($double, 'mock');140    }141    /**142     * Injects a spy.143     *144     * @param MockInterface|CompositeExpectation|string $double145     *146     * @return MockInterface147     */148    protected function injectSpy($double)149    {150        return $this->inject($double, 'spy');151    }152    /**153     * Injects a RemoteWebDriver double into the SeleniumTestCase.154     *155     * @param MockInterface|CompositeExpectation|string $double156     *157     * @return RemoteWebDriver158     */159    protected function injectWebDriver($double = RemoteWebDriver::class)160    {161        // Default behavior for mock doubles162        $double = $this->normalizeDouble($double)->shouldReceive('quit')->byDefault();163        return $this->injectDependency($double, 'setWebDriver');164    }165    /**166     * Injects a DesiredCapabilities double into the SeleniumTestCase.167     *168     * @param MockInterface|CompositeExpectation|string $double169     *170     * @return DesiredCapabilities171     */172    protected function injectDesiredCapabilities($double = DesiredCapabilities::class)173    {174        return $this->injectDependency($double, 'setDesiredCapabilities');175    }176    /**177     * Injects a WebDriverBy double into the SeleniumTestCase.178     *179     * @param MockInterface|CompositeExpectation|string $double180     *181     * @return WebDriverBy182     */183    protected function injectWebDriverBy($double = WebDriverBy::class)184    {185        return $this->injectDependency($double, 'setWebDriverBy');186    }187    /**188     * Injects a Filesystem double into the SeleniumTestCase.189     *190     * @param MockInterface|CompositeExpectation|string $double191     *192     * @return Filesystem193     */194    protected function injectFilesystem($double = Filesystem::class)195    {196        return $this->injectDependency($double, 'setFilesystem');197    }198    /**199     * Injects a Locator double into the SeleniumTestCase.200     *201     * @param MockInterface|CompositeExpectation|string $double202     *203     * @return Filesystem204     */205    protected function injectLocator($double = Locator::class)206    {207        return $this->injectDependency($double, 'setLocator');208    }209    /**210     * Injects a dependency double into the SeleniumTestCase.211     *212     * @param MockInterface|CompositeExpectation|string $double213     * @param string|null $setter214     *215     * @return MockInterface216     */217    protected function injectDependency($double, $setter = null)218    {219        $double   = $this->normalizeDouble($double);220        $setter = $setter ? $setter : $this->getDependencySetter($double);221        $this->$setter($double);222        return $double;223    }224    /**225     * Returns setter method name from a dependency mock object.226     *227     * @param MockInterface $double228     *229     * @return string230     */231    private function getDependencySetter($double)232    {233        return $this->getDependencyMethodName($double, 'set');234    }235    /**236     * Returns injector method name from a dependency mock object.237     *238     * @param MockInterface $double239     *240     * @return string241     */242    private function getDependencyInjector($double)243    {244        return $this->getDependencyMethodName($double, 'inject');245    }246    /**247     * Returns setter/injector method name for a dependency mock.248     *249     * @param MockInterface $double250     * @param string $type251     *252     * @return string253     * @throws \Exception254     */255    private function getDependencyMethodName(MockInterface $double, $type)256    {257        $fqn    = $this->getDependencyFqn($double);258        $method = $type . $this->getDependencyName($this->getDependencyClass($fqn));259        if (method_exists($this, $method)) {260            return $method;261        }262        throw new \Exception("Could not find the \"$type\" method for: " . get_class($double));263    }264    /**265     * Returns FQN of the test double object.266     *267     * This is too much, I know :/268     *269     * @param MockInterface $double270     *271     * @return string272     * @throws \Exception273     */274    private function getDependencyFqn($double)275    {276        $fqn = preg_replace(277            '/^Mockery\\\(\d+)\\\/',278            '',279            str_replace('_', '\\', get_class($double))280        );281        if (class_exists($fqn)) {282            return $fqn;283        }284        throw new \Exception('Could not extract the FQN of original class from mock: ' . get_class($double));285    }286    /**287     * Returns the short class name for a FQN.288     *289     * @param string $fqn290     *291     * @return string292     */293    private function getDependencyClass($fqn)294    {295        return ltrim(strrchr($fqn, '\\'), '\\');296    }297    /**298     * Returns the dependency name that SUT uses.299     *300     * @param string $dependencyClass301     *302     * @return string303     */304    private function getDependencyName($dependencyClass)305    {306        $exceptions = [307            'RemoteWebDriver' => 'WebDriver',308        ];309        return key_exists($dependencyClass, $exceptions)310            ? $exceptions[$dependencyClass]311            : $dependencyClass;312    }313    /**314     * Normalizes a test double object.315     *316     * @param MockInterface|CompositeExpectation|string $double317     * @param string $doubleType318     *319     * @return MockInterface320     * @throws \Exception321     */322    private function normalizeDouble($double, $doubleType = 'mock')323    {324        if (is_string($double)) {325            $double = $this->$doubleType($double);326        } elseif ($double instanceof CompositeExpectation) {327            $double = $double->getMock();328        }329        if (! $double instanceof MockInterface) {330            throw new \Exception('Cannot inject an invalid test double, what the fuck?!');331        }332        return $double;333    }334}...ApiHelper.php
Source:ApiHelper.php  
...4use App\Api\HttpClient;5use App\Api\ApiClient;6use GuzzleHttp\ClientInterface;7use Mockery as m;8use Mockery\CompositeExpectation;9use Mockery\MockInterface;10use Psr\Http\Message\RequestInterface;11use Psr\Http\Message\ResponseInterface;12trait ApiHelper13{14    /**15     * @return HttpClient|MockInterface16     */17    private function createHttpClient(): HttpClient18    {19        return m::spy(HttpClient::class);20    }21    private function mockHttpClientGet(MockInterface $httpClient, $response, string $path, array $data, array $headers): CompositeExpectation22    {23        return $httpClient24            ->shouldReceive('get')25            ->with($path, $data, $headers)26            ->andThrow($response);27    }28    /**29     * @param ResponseInterface|\Exception $response30     */31    private function mockHttpClientPost(MockInterface $httpClient, $response, string $path, array $data, array $headers): CompositeExpectation32    {33        return $expectation = $httpClient34            ->shouldReceive('post')35            ->with($path, $data, $headers)36            ->andThrow($response);37    }38    /**39     * @return ClientInterface|MockInterface40     */41    private function createGuzzleClient(): ClientInterface42    {43        return m::spy(ClientInterface::class);44    }45    private function mockGuzzleClientRequest(46        MockInterface $guzzleClient,47        $response,48        string $method,49        string $uri,50        array $options51    ): CompositeExpectation {52        return $guzzleClient53            ->shouldReceive('request')54            ->with($method, $uri, $options)55            ->andThrow($response);56    }57    /**58     * @return ResponseInterface|MockInterface59     */60    private function createResponse(): ResponseInterface61    {62        return m::spy(ResponseInterface::class);63    }64    private function mockResponseGetStatusCode(MockInterface $response, int $statusCode): CompositeExpectation65    {66        return $response67            ->shouldReceive('getStatusCode')68            ->andReturn($statusCode);69    }70    private function mockResponseGetHeader(MockInterface $response, array $header, string $name): CompositeExpectation71    {72        return $response73            ->shouldReceive('getHeader')74            ->with($name)75            ->andReturn($header);76    }77    private function mockResponseGetBody(MockInterface $response, string $body): CompositeExpectation78    {79        return $response80            ->shouldReceive('getBody')81            ->andReturn($body);82    }83    /**84     * @return ApiClient|MockInterface85     */86    private function createApiClient(): ApiClient87    {88        return m::spy(ApiClient::class);89    }90    private function mockApiClientRegister(91        MockInterface $onizeApiClient,92        $response,93        string $email,94        string $password95    ): CompositeExpectation {96        $expectation = $onizeApiClient97            ->shouldReceive('register')98            ->with($email, $password);99        if ($response instanceof \Exception) {100            return $expectation->andThrow($response);101        }102        return $expectation->andReturn($response);103    }104    private function mockApiClientAuthenticatedUser(MockInterface $apiClient, $response): CompositeExpectation105    {106        $expectation = $apiClient->shouldReceive('authenticatedUser');107        if ($response instanceof \Exception) {108            return $expectation->andThrow($response);109        }110        return $expectation->andReturn($response);111    }112    private function mockApiClientAuthenticate(MockInterface $apiClient, $response, string $email, string $password): CompositeExpectation113    {114        $expectation = $apiClient115            ->shouldReceive('authenticate')116            ->with($email, $password);117        if ($response instanceof \Exception) {118            return $expectation->andThrow($response);119        }120        return $expectation->andReturn($response);121    }122    /**123     * @return ValidationException|MockInterface124     */125    private function createValidationException(): ValidationException126    {...TestStageEventsExpectationsBuilder.php
Source:TestStageEventsExpectationsBuilder.php  
1<?php2namespace Morebec\Orkestra\EventSourcing\Testing;3use Morebec\Orkestra\EventSourcing\Testing\Expectation\CompositeExpectation;4use Morebec\Orkestra\EventSourcing\Testing\Expectation\Events\ExactNumberOfEventsExpectation;5use Morebec\Orkestra\EventSourcing\Testing\Expectation\Events\NoEventIsOfTypeExpectation;6use Morebec\Orkestra\EventSourcing\Testing\Expectation\Events\OneEventIsOfTypeExpectation;7use Morebec\Orkestra\EventSourcing\Testing\Expectation\TestStageExpectationInterface;8class TestStageEventsExpectationsBuilder9{10    private CompositeExpectation $composite;11    private TestScenarioBuilder $scenarioBuilder;12    private TestStage $stage;13    public function __construct(TestScenarioBuilder $scenarioBuilder, TestStage $stage, CompositeExpectation $compositeExpectation)14    {15        $this->scenarioBuilder = $scenarioBuilder;16        $this->stage = $stage;17        $this->composite = $compositeExpectation;18    }19    /**20     * Adds an expectation to this stage.21     *22     * @param OneEventIsOfTypeExpectation $expectation23     *24     * @return TestStageEventsExpectationsBuilder25     */26    public function expect(TestStageExpectationInterface $expectation): self27    {...CompositeExpectation
Using AI Code Generation
1require_once 'CompositeExpectation.php';2require_once 'Mockery.php';3require_once 'MockeryTestCase.php';4require_once 'MockeryPHPUnitIntegration.php';5require_once 'MockeryPHPUnitIntegrationTest.php';6require_once 'MockeryTestListener.php';7require_once 'Test.php';8require_once 'TestListener.php';9require_once 'TestListenerForPHPUnit.php';10require_once 'TestListenerForPHPUnitTest.php';11require_once 'TestListenerForPHPUnitTestRunner.php';12require_once 'TestListenerForPHPUnitTestRunnerTest.php';13require_once 'TestListenerForPHPUnitTestRunnerV6.php';14require_once 'TestListenerForPHPUnitTestRunnerV6Test.php';15require_once 'TestListenerForPHPUnitTestRunnerV6WithNamespacedTestCase.php';16require_once 'TestListenerForPHPUnitTestRunnerV6WithNamespacedTestCaseTest.php';17require_once 'TestListenerForPHPUnitTestRunnerV6WithNamespacedTestCaseWithNamespaceInTestName.php';18require_once 'TestListenerForPHPUnitTestRunnerV6WithNamespacedTestCaseWithNamespaceInTestNameTest.php';CompositeExpectation
Using AI Code Generation
1use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;2use Mockery\CompositeExpectation;3use Mockery\Expectation;4use Mockery\ExpectationInterface;5use Mockery\MockInterface;6use Mockery\Mockery;7use PHPUnit\Framework\TestCase;8{9    use MockeryPHPUnitIntegration;10    public function testCompositeExpectation()11    {12        $mock = Mockery::mock('class');13        $compositeExpectation = new CompositeExpectation();14        $compositeExpectation->addExpectation($mock->shouldReceive('method1')->once());15        $compositeExpectation->addExpectation($mock->shouldReceive('method2')->once());16        $compositeExpectation->addExpectation($mock->shouldReceive('method3')->once());17        $this->assertTrue($compositeExpectation->isMet());18    }19}20.                                                                   1 / 1 (100%)21OK (1 test, 1 assertion)CompositeExpectation
Using AI Code Generation
1require_once 'vendor/autoload.php';2use Mockery\Adapter\Phpunit\MockeryTestCase;3use Mockery\CompositeExpectation;4{5    public function testCompositeExpectation()6    {7        $mock = Mockery::mock('alias:Mockery\CompositeExpectation');8        $mock->shouldReceive('add')->with('foo')->once();9        $mock->shouldReceive('add')->with('bar')->once();10        $mock->shouldReceive('add')->with('baz')->once();11        $composite = new CompositeExpectation();12        $composite->add('foo');13        $composite->add('bar');14        $composite->add('baz');15    }16}17require_once 'vendor/autoload.php';18use Mockery\Adapter\Phpunit\MockeryTestCase;19use Mockery\CompositeExpectation;20{21    public function testCompositeExpectation()22    {23        $mock = Mockery::mock('alias:Mockery\CompositeExpectation');24        $mock->shouldReceive('add')->with('foo')->once();25        $mock->shouldReceive('add')->with('bar')->once();26        $mock->shouldReceive('add')->with('baz')->once();27        $composite = new CompositeExpectation();28        $composite->add('foo');29        $composite->add('bar');30        $composite->add('baz');31    }32}33require_once 'vendor/autoload.php';34use Mockery\Adapter\Phpunit\MockeryTestCase;35use Mockery\CompositeExpectation;36{37    public function testCompositeExpectation()38    {39        $mock = Mockery::mock('alias:Mockery\CompositeExpectation');40        $mock->shouldReceive('add')->with('foo')->once();41        $mock->shouldReceive('add')->with('bar')->once();42        $mock->shouldReceive('add')->with('baz')->once();43        $composite = new CompositeExpectation();44        $composite->add('foo');45        $composite->add('bar');46        $composite->add('baz');47    }48}49require_once 'vendor/autoload.php';CompositeExpectation
Using AI Code Generation
1require_once 'CompositeExpectation.php';2require_once 'Mockery.php';3require_once 'MockeryTestCase.php';4require_once 'MockeryPHPUnitIntegration.php';5require_once 'ExpectationDirector.php';6require_once 'Expectation.php';7require_once 'ExpectationDirector.php';8require_once 'CompositeExpectation.php';9require_once 'CountValidator.php';10require_once 'Matcher.php';11require_once 'MatcherAbstract.php';12require_once 'MatcherCType.php';13require_once 'MatcherType.php';14require_once 'MatcherAny.php';15require_once 'MatcherNot.php';16require_once 'MatcherSubset.php';17require_once 'MatcherHasEntry.php';18require_once 'MatcherHasValue.php';19require_once 'MatcherSameSize.php';20require_once 'MatcherContains.php';21require_once 'MatcherContainsOnly.php';22require_once 'MatcherEndsWith.php';23require_once 'MatcherStartsWith.php';24require_once 'MatcherIsInstanceOf.php';25require_once 'MatcherIsset.php';26require_once 'MatcherIsEmpty.php';27require_once 'MatcherIsNumeric.php';28require_once 'MatcherIsReadable.php';29require_once 'MatcherIsWritable.php';CompositeExpectation
Using AI Code Generation
1$mock = Mockery::mock('MyClass');2$mock->shouldReceive('doSomething')->once()->with('foo', Mockery::on(function($arg) {3    return $arg == 'bar';4}));5$mock = Mockery::mock('MyClass');6$mock->shouldReceive('doSomething')->once()->with('foo', Mockery::on(function($arg) {7    return $arg == 'bar';8}));9Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_MyClass::doSomething('foo', 'bar'). Either the method was unexpected or its arguments matched no expected argument list for this methodCompositeExpectation
Using AI Code Generation
1$compositeExpectation = new \Mockery\ExpectationComposite();2$compositeExpectation->shouldReceive('someMethod')->andReturn(true);3$compositeExpectation->shouldReceive('someMethod')->andReturn(true);4$mock = \Mockery::mock('Class');5$mock->shouldReceive('someMethod')->andReturnUsing(function() use ($compositeExpectation) {6    return $compositeExpectation;7});CompositeExpectation
Using AI Code Generation
1$mock = Mockery::mock('Mockery_Testing_MockInterface');2$mock->shouldReceive('method1')3->once()4->with(Mockery::on(function($arg) {5return $arg instanceof Mockery_Testing_MockInterface;6}))7->andReturn('foo');8$mock->method1($mock);9$mock = Mockery::mock('Mockery_Testing_MockInterface');10$mock->shouldReceive('method1')11->once()12->with(Mockery::on(function($arg) {13return $arg instanceof Mockery_Testing_MockInterface;14}))15->andReturn('foo');16$mock->method1($mock);17$mock = Mockery::mock('Mockery_Testing_MockInterface');18$mock->shouldReceive('method1')19->once()20->with(Mockery::on(function($arg) {21return $arg instanceof Mockery_Testing_MockInterface;22}))23->andReturn('foo');24$mock->method1($mock);25$mock = Mockery::mock('Mockery_Testing_MockInterface');26$mock->shouldReceive('method1')27->once()28->with(Mockery::on(function($arg) {29return $arg instanceof Mockery_Testing_MockInterface;30}))31->andReturn('foo');32$mock->method1($mock);33$mock = Mockery::mock('Mockery_Testing_MockInterface');34$mock->shouldReceive('method1')35->once()36->with(Mockery::on(function($arg) {37return $arg instanceof Mockery_Testing_MockInterface;38}))39->andReturn('foo');40$mock->method1($mock);41$mock = Mockery::mock('Mockery_Testing_MockInterface');42$mock->shouldReceive('method1')43->once()44->with(Mockery::on(function($arg) {45return $arg instanceof Mockery_Testing_MockInterface;46}))47->andReturn('foo');48$mock->method1($mock);Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.
Test now for FreeGet 100 minutes of automation test minutes FREE!!
