0

I have the following unit test but I don't get back the needed values. Maybe I don't understand how this works correctly.

class TestClass
{
    public function getData()
    {
        $id = 1123;
        return $id;
    }
}

class Test_ClassTesting extends PHPUnit_Framework_TestCase
{

    public function test_addData()
    {
        $stub = $this->getMock('TestClass');


        $stub
            ->expects($this->any())
            ->method('getData')
            ->will($this->returnValue('what_should_i_put_here_to_get id from TESTCLASS'));


        $y = $stub->getData();

    }
}
b.b3rn4rd
  • 8,494
  • 2
  • 45
  • 57
Tudor Ravoiu
  • 2,130
  • 8
  • 35
  • 56
  • It's not very clear what you're trying to accomplish. If you want a stub, then hard code a stub value in `returnValue`. If you want to get the `1123` value, then just instantiate `TestClass` and drop the usage of mocks/stubs. – Ionuț G. Stan Apr 08 '14 at 10:21
  • It's also not clear what you're trying to test, as there are no assertions in your snippet. – Ionuț G. Stan Apr 08 '14 at 10:22
  • Your code snippet works fine. You should put what ever id value you want for your test as the parameter in the `$this->returnValue()` – Schleis Apr 08 '14 at 13:30

1 Answers1

0

As the commenters have said, you simply return the value desired.

class TestClass
{
    public function getData()
    {
        $id = 1123;
        return $id;
    }
}

class Test_ClassTesting extends PHPUnit_Framework_TestCase
{
    public function test_addData()
    {
        $stub = $this->getMock('TestClass');   // Original Class is not used now
        $stub
            ->expects($this->any())
            ->method('getData')
            ->will($this->returnValue(4444));  // Using different number to show stub works, not actual function
        $this->assertEquals(4444, $stub->getData());
    }

    public function test_addDataWithoutStub()
    {
        $object = new TestClass();
        $this->assertEquals(1123, $object->getData());
    }
}
Steven Scott
  • 10,234
  • 9
  • 69
  • 117