0

I am learnig about test doubles, but I'm a little confused about the difference between Mocks and Stubs.

So, looking for some references about this topic, I found this article (is a good article, but some examples are a little bit confusing)

Then, I was following the examples in my IDE, however, the examples about Mocks and Stubs are the same.

Stubs example:

class A
{
    public function calculate() {    }
}

class B
{
    private A $a;
    public $value;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function setValue()
    {
        $this->value = $this->a->calculate();
    }
}

class StubsTest extends \PHPUnit\Framework\TestCase
{
    public function testValueCorrect()
    {
        $a = $this->createStub(A::class);
        $a
            ->method('calculate')
            ->willReturn(10);

        $b = new B($a);
        $b->setValue();

        $this->assertEquals(10, $b->value);
    }
}

Mock example:

use PHPUnit\Framework\TestCase;

class A {
    public function calculate() {    }
    public function doSomething() {    }
}

class B {

    private $a;
    public $value;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function setValue()
    {
        $this->value = $this->a->calculate();
    }

    public function doSomethingWithA()
    {
        $this->a->doSomething();
    }
}

class MockTest extends TestCase
{
    public function testValueCorrect()
    {
        $a = $this->createStub(A::class);
        $a
            ->method('calculate')
            ->willReturn(10);

        $b = new B($a);
        $b->setValue();

        $this->assertEquals(10, $b->value);
    }
}

What the real difference between both? These code examples above are valid?

izmatlDev
  • 13
  • 4

0 Answers0