Mocks vs Stubs in PHPUnit

1

How can I differentiate in PHPUnit a Stub from a Mock.

The Stubs verify status, and only dedicate themselves to returning specific answers when called. The PHPUnit documentation on this is clear and the example is very illustrative:

    // Create a stub for the SomeClass class.
    $stub = $this->createMock(SomeClass::class);

    // Configure the stub.
    $stub->method('doSomething')
         ->willReturn('foo');

    // Calling $stub->doSomething() will now return 'foo'.
    $this->assertEquals('foo', $stub->doSomething());

When the method that is configured is called, it will return the response indicated.

In the case of the Mocks they verify behavior, they are not interested in returning values, but check that they pass through certain methods, how many times they pass, etc. But in PHPUnit this is not so clear, since there are no verify () methods (as they exist in others).

How would the creation of a Mock (not a Stub) be in PHPUnit?

    
asked by RodriKing 30.08.2017 в 20:30
source

1 answer

1

To configure a mock, you must use the expects method, which allows you to configure expected calls to our mock:

$mock = $this->getMockBuilder(SomeClass::class)
                 ->setMethods(['metodoEjemplo'])
                 ->getMock();

$mock->expects($this->once())
     ->method('metodoEjemplo')
     ->with(1, 2)
     ->willReturn(3);

As in configuring the Stubs, we can indicate the arguments that the call should receive by with , as well as the return value that will return the call by willReturn .

The configuration of the Mocks is also documented on the PHPUnit website:

link

    
answered by 07.12.2017 в 11:17