0

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);
}

3 Answers 3

2

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());
    }  
}
Sign up to request clarification or add additional context in comments.

Comments

1
$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));

1 Comment

They're the same when they pass, but when assertEquals fails, it will tell you where the difference is, whereas assertTrue will just tell you that false is not true.
1

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.