Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if string contains another string in PHPUnit?

Tags:

php

phpunit

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...

like image 374
TheStoryCoder Avatar asked Jun 03 '14 13:06

TheStoryCoder


1 Answers

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.

like image 135
Schleis Avatar answered Oct 17 '22 15:10

Schleis