Behavior verification tools.
Given a log of interactions performed on some objects, this library allows to verify that some or all of them were performed correctly.
composer require netmosfera/behave
Simple example:
- Verify that a property named
var3
was retrieved on$obj1
. - Verify that a property named
var5
was retrieved on$obj2
.
<?php
use Netmosfera\Behave\Log\GetInteraction;
use Netmosfera\Behave\Verification\Interactions\Result;
use function Netmosfera\Behave\get;
use function Netmosfera\Behave\any;
use function Netmosfera\Behave\every;
//[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
// This is the list of the interactions performed by the program; it is not meant to be
// compiled manually but it should be automatically generated by "test double" objects,
// like a "spies" or a "mocks":
$obj1 = new class(){ /* irrelevant for the example */ };
$obj2 = new class(){ /* irrelevant for the example */ };
$obj3 = new class(){ /* irrelevant for the example */ };
$interactions[] = new GetInteraction($obj1, "var1", "return1", FALSE);
$interactions[] = new GetInteraction($obj2, "var2", "return2", FALSE);
$interactions[] = new GetInteraction($obj1, "var3", "return3", FALSE); // ✓
$interactions[] = new GetInteraction($obj3, "var4", "return4", FALSE);
$interactions[] = new GetInteraction($obj2, "var5", "return5", FALSE); // ✓
$interactions[] = new GetInteraction($obj1, "var6", "return6", FALSE);
$interactions[] = new GetInteraction($obj3, "var7", "return7", FALSE);
//[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
// Verify that the program did `get()` `$obj1->var3`, and that it returned `any()` object.
$constraint = get($obj1, "var3", any(), /* ignore these for now: */ FALSE, FALSE);
// Attempts to fulfill the constraint with the log of interactions:
$result = $constraint->fulfill($interactions);
// If the constraint is fulfilled, `fulfill()` returns a `Result` object.
assert($result instanceof Result);
//[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
// The constraint for the second interaction would look very similar to the first one, but
// the interesting part is that we can combine them both in one expression only:
$constraint = every([
get($obj1, "var3", any(), /* ignore these for now: */ FALSE, FALSE),
get($obj2, "var5", any(), /* ignore these for now: */ FALSE, FALSE),
], /* ignore this for now: */ FALSE);
$result = $constraint->fulfill($interactions);
assert($result instanceof Result);