How to test if string contains another string in PHPUnit?

TheStoryCoder picture TheStoryCoder · Jun 3, 2014 · Viewed 38.4k times · Source

I can't seem to find an assertion in PHPUnit that simply tests if a string is contained somewhere in another string. Trying to do something like this:

public function testRecipe() {

    $plaintext = get_bread_recipe();

    $this->assertStringContains('flour', $plaintext);

}

What real assertion would I put instead of assertStringContains ? I would prefer not having to worry about regex in this case because there is absolutely no need for it.

It's so simple that there must be something I have overlooked, but I just can't figure it out! Funny enough there is assertStringStartsWith() and assertStringEndsWith()!

Update: I know strpos() !== false could be used but I'm looking for something cleaner. If I just use vanilla PHP functions anyway what's the whole point with all the assertions then...

Answer

Schleis picture Schleis · Jun 3, 2014

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.