How to test if string contains another string in PHPUnit? How to test if string contains another string in PHPUnit? php php

How to test if string contains another string in PHPUnit?


As you could tell assertContains is for checking that an array contains a value.

Looking to see if the string contains a substring, your simplest query would be to use assertRegexp()

$this->assertRegexp('/flour/', $plaintext);

You would just need to add the delimiters.

If you really want to have an assertStringContains assertion, you can extend PHPUnit_Framework_TestCase and create your own.

UPDATE

In the latest version of PHPUnit, assertContains will work on strings.


You can always hide the ugliness inside a custom assertion method, so basically I would have a BaseTestCase class which inherits from the phpunit test case which you could use to have your own library of reusable assertions (see http://xunitpatterns.com/Custom%20Assertion.html).. (In php 5.4 you can use traits as well, imho assertion libraries are one of the cases where traits actually are useful)..I always introduce quite a few custom assertions in my projects, often domain specific. And yes, some are ugly too:) well, I guess that's what encapsulation is there for... Amongst things...:)

UPDATE:I just checked and 'assertContains' and 'assertNotContains' actually also operate on strings as well as arrays (and anything that implements 'Traversable'):

function test_Contains(){    $this->assertContains("test", "this is a test string" );    $this->assertNotContains("tst", "this is a test string");}


2019 and PHPUnit 8.0 update

assertContains() is deprecated since PHPUnit 8.0, see issue #3425.


Now the specific method is recommended (see issue #3422):

$plaintext = 'I fell on the flour';$this->assertStringContainsString('flour', $plaintext);

TIP: Upgrade instantly with Rector and PHPUnit 8.0 set.