phrity/net-mock

Mock layer for phrity/net-stream

2.1.0 2024-09-14 12:10 UTC

This package is auto-updated.

Last update: 2024-10-14 12:17:56 UTC


README

Build Status Coverage Status

Introduction

Writing tests that use streams is problematic. This library provides a mocking layer for phrity/net-stream, allowing developers to verify and mock stream interactions.

Installation

Install with Composer;

composer require phrity/net-mock

Usage

The classes in this library are fully compatible with those of the net-stream library. By default, calling the mock classes will propagate into the real implementation classes.

use Phrity\Net\StreamFactory as RealStreamFactory;
use Phrity\Net\Mock\StreamFactory as MockStreamFactory;

// Your code should allow setting stream classes
$my_stream_user = new StreamUsingClass();
$my_stream_user->setStreamfactory($mock ? new MockStreamFactory() : new RealStreamFactory());
$my_stream_user->run();

Log interactions

By adding a PSR-3 compatible logger, all calls will be logged. The library includes a simple EchoLogger, but any compatible logger is usable.

use Phrity\Net\Mock\EchoLogger;
use Phrity\Net\Mock\Mock;
use Phrity\Net\Mock\StreamFactory;

Mock::setLogger(new EchoLogger());

$my_stream_user = new StreamUsingClass();
$my_stream_user->setStreamfactory(new StreamFactory());
$my_stream_user->run();

Mock interactions

By registring a callback handler, all calls will pass through the callback instead.

use Phrity\Net\Mock\Mock;
use Phrity\Net\Mock\StreamFactory;

Mock::setCallback(function (int $counter, string $method, array $params, callable $default) {
    // Assert call and parameters
    // The returned value will be passed back to calling code.
    // If you want to return the result of original code, use the $default callable
    return $default();
});

$my_stream_user = new StreamUsingClass();
$my_stream_user->setStreamfactory(new StreamFactory());
$my_stream_user->run();

Versions