Vincent
Vincent

Reputation: 630

PHPUnit - using assertions in external object

I'm working on a tool exporting tests as PHP/PHPUnit and I'm facing a small problem. To explain briefly, the test scripts only contain calls to an actionwords object, which contains all the logic of the test (in order to factors various steps from different test scenario). An example might be clearer:

require_once('Actionwords.php');

class CoffeeMachineHiptestPublisherSampleTest extends PHPUnit_Framework_TestCase {
  public $actionwords = new Actionwords();


  public function simpleUse() {
    $this->actionwords->iStartTheCoffeeMachine();
    $this->actionwords->iTakeACoffee();
    $this->actionwords->coffeeShouldBeServed();
  }
}

Here in the coffeeShouldBeServed method, I need to run an assertion, but that's not possible as the Actionwords class does not extend PHPUnit_Framework_TestCase (and I'm not sure it should, it's not a test case, just a set of helpers).

Currently the solution I found is to pass the tests object to the action words and use the reference for the assertions, something like that.

class CoffeeMachineHiptestPublisherSampleTest extends PHPUnit_Framework_TestCase {
  public $actionwords;

  public function setUp() {
    $this->actionwords = new Actionwords($this);
  }
}

class Actionwords {
  var $tests;

  function __construct($tests) {
    $this->tests = $tests;
  }

  public function coffeeShouldBeServed() {
    $this->tests->assertTrue($this->sut->coffeeServed);
  }
}

It works fine but I don't find it really elegant. I'm not a PHP developer so there might be some better solutions that feel more "php-ish".

Thanks in advance, Vincent

Upvotes: 1

Views: 42

Answers (1)

Sebastian Bergmann
Sebastian Bergmann

Reputation: 8336

The assertion methods are static so you can use PHPUnit_Framework_Assert::assertEquals(), for instance.

Upvotes: 2

Related Questions