nowiko
nowiko

Reputation: 2557

PhpUnit and string

I started learning PhpUnit and testing. I have a method which returns string, how I can write a test to check if this method returns string. Here is the code I have at this moment:

Method:

 /**
 * @return string
 */
public function living()
{
    return 'Happy!';
}

Test:

 public $real;
public $expected;

public function testLiving()
{
    $this->expected = 'Happy';
    $this->real = 'Speechless';
    $this->assertTrue($this->expected == $this->real);
}

Upvotes: 0

Views: 277

Answers (3)

Ashish Awasthi
Ashish Awasthi

Reputation: 1502

You can use $this->assertInternalType to check for type of the data, and if you want to test such functions use Test Doubles or Mocking Object.

Here is the code giving full demo on how you can test:

//Your Class
class StringReturn {
    public function returnString()
    {
        return 'Happy';
    }
}


//Your Test Class
class StringReturnTest extends PHPUnit_Framework_TestCase
{
    public function testReturnString()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('StringReturn')
        ->disableOriginalConstructor()
        ->getMock();

        // Configure the stub.
        $stub->method('returnString')
        ->willReturn('Happy');


        $this->assertEquals('Happy', $stub->returnString());
        $this->assertInternalType('string', $stub->returnString());
    }  
}

Upvotes: 2

Ilya Isaev
Ilya Isaev

Reputation: 197

Test check only positive. You need check negative too.

public function testLiving()
{
    $classWithLivingMethod = new ClassWithLivingMethod;
    $this->assertTrue(is_string($classWithLivingMethod->living()));
    $this->assertEquals('Happy', $classWithLivingMethod->living());
}

Upvotes: 1

po_taka
po_taka

Reputation: 1856

$this->assertTrue($this->expected == $this->real);

is the same as

$this->assertEquals($this->expected, $this->real);

See https://phpunit.de/manual/current/en/appendixes.assertions.html#appendixes.assertions.assertEquals

Both check if given variables are equal.

You could check if variable is string

$this->assertTrue(is_string($this->real));

Upvotes: 1

Related Questions