Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Last active May 23, 2022 12:28
Show Gist options
  • Star 112 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save mathiasverraes/9046427 to your computer and use it in GitHub Desktop.
Save mathiasverraes/9046427 to your computer and use it in GitHub Desktop.
A unit testing framework in a tweet.
<?php
require_once 'TestFrameworkInATweet.php';
it("should sum two numbers", 1+1==2);
it("should display an X for a failing test", 1+1==3);
done();
<?php
function it($m,$p){echo ($p?'✔︎':'✘')." It $m\n"; if(!$p){$GLOBALS['f']=1;}}function done(){if(@$GLOBALS['f'])die(1);}
@gmazzap
Copy link

gmazzap commented Nov 29, 2017

I gave up to colors, but

  • use standard output/error for the success/failure output
  • add some mimimum formatting
  • add possibility to pass a callback as predicate
<?php
function it($m,$p){ $d=debug_backtrace(0)[0];
 is_callable($p) and $p=$p();
 global $e;$e=$e||!$p;
 $o=($p?"":"")." It $m";
 fwrite($p?STDOUT:STDERR,$p?"$o\n":"$o FAIL: {$d['file']} #{$d['line']}\n");
}

register_shutdown_function(function(){global $e; $e and die(1);});

Example:

it('should display an X for a failing test.', 1+1===3);

it('should append to an ArrayIterator.', function() {
  $iterator = new ArrayIterator();
  $iterator->append('test');
  return count($iterator) === 1 && $iterator->current() === 'test';
});

it('should pass test for InvalidArgumentException exception.', function() {
  try {
    throw new InvalidArgumentException();
  } catch(InvalidArgumentException $e) {
    return true;
  }
});

with output:

✘ It should display an X for a failing test. FAIL: /path/to/file.php #11
✔ It should append to an ArrayIterator.
✔ It should pass test for InvalidArgumentException exception.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment