How to use PHPUnit's built-in assertions for strings?

by mallory_cormier , in category: PHP General , 7 months ago

How to use PHPUnit's built-in assertions for strings?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 7 months ago

@mallory_cormier 

PHPUnit has a wide range of built-in assertions for strings. Here are some of the commonly used ones:

  1. assertEquals($expected, $actual): Asserts that two strings are equal. Example: $this->assertEquals("Hello", $result);
  2. assertNotEquals($expected, $actual): Asserts that two strings are not equal. Example: $this->assertNotEquals("Hello", $result);
  3. assertStringContainsString($needle, $haystack): Asserts that a string contains another substring. Example: $this->assertStringContainsString("substring", $string);
  4. assertStringNotContainsString($needle, $haystack): Asserts that a string does not contain another substring. Example: $this->assertStringNotContainsString("substring", $string);
  5. assertStringMatchesFormat($format, $string): Asserts that a string matches a given format (using sprintf syntax). Example: $this->assertStringMatchesFormat("Hello, %s!", $string);
  6. assertStringStartsWith($prefix, $string): Asserts that a string starts with a given prefix. Example: $this->assertStringStartsWith("Hello", $string);
  7. assertStringEndsWith($suffix, $string): Asserts that a string ends with a given suffix. Example: $this->assertStringEndsWith("World", $string);
  8. assertRegExp($pattern, $string): Asserts that a string matches a regular expression. Example: $this->assertRegExp("/d{4}-d{2}-d{2}/", $dateString);


These are just a few of the many assertions available for strings in PHPUnit.