Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use PHPUnit assertions without extending PHPUnit_Framework_TestCase?

Maybe the question comes across as weird, but here is the problem that I'm trying to solve... first of all, please keep in mind I am more of a Java developer getting used to working with PHP, so maybe my thought process is the problem!

I am testing a web site that I have built with Symfony. For my component testing, I create my test class extending WebTestCase and my test I have a set of assertions like the following to verify that the page title is where I want it and containing what I expect:

$text = "Page Title";
$selector = "h2#pageHeading";
$this->assertEquals(1, $crawler->filter($selector)->count(), "Found wrong number of elements using selector ".$selector);
$this->assertEquals(trim($text),
        trim($crawler->filter($selector)->text()),
        "Element $selector didn't have expected text");

Then I write more tests for other pages within the site, and in all of them I want to test the title is there as it should be, so to be able to reuse code I refactor the above into a function in parent class that the other test classes reuse:

function assertPageTitle($text) {
    $selector = "h2#pageHeading";
    $this->assertEquals(1, $crawler->filter($selector)->count(), "Found wrong number of elements using selector ".$selector);
    $this->assertEquals(trim($text),
            trim($crawler->filter($selector)->text()),
            "Element $selector didn't have expected text");
}

And I call that method in my tests. As tests develop there are more similar "complex assertions" that I can refactor, and all of them go to the parent class, thus bloating my parent class into a massive assertion container:

protected function assertSelectedOptionContainsTextValue($selector, $text, $value, $crawler) {
    ...
}

protected function assertMenusContainItems($menus, $crawler) {
    ...
}

protected function assertErrorMessageShown($message, $crawler) {
    ...
}

... (more and more) ...

You get the idea. My next thought at this point is to refactor all this "complex assertions" into other classes, probably following the Page Object pattern, but then the other classes won't have access to the assertEquals method unless those other classes also extend WebTestCase or at least PHPUnit_Framework_TestCase, which doesn't seem a very good idea...

So is there an easy way to access the assertEquals method (and related) without having to extend the base PHPUnit classes? Can I use composition somehow?

like image 263
quiram Avatar asked Dec 08 '22 04:12

quiram


1 Answers

PHPUnit's built-in assertions are implemented as public static methods in the PHPUnit_Framework_Assert class. Just invoke them as PHPUnit_Framework_Assert::assertTrue(), for instance.

like image 123
Sebastian Bergmann Avatar answered Dec 10 '22 23:12

Sebastian Bergmann