I'll-Be-Back I'll-Be-Back - 3 years ago 126
PHP Question

Does Unit Test mean that the test has to be mocked?

Does Unit Test mean that the test has to be mocked or definition of Unit Test can be without mocked?

For example below, this test is mocked, so it is unit test:

/**
* @test
*/
public function it_should_return_true_if_ssh_client_is_connected()
{
$this->phpSecLibShh->shouldReceive('isConnected')->andReturn(true)->once();

$this->assertTrue($this->shell->connected($this->phpSecLibShh));
}


Example below, is this Unit Test or Integration Test? I am not clear about this:

/**
* @test
*/
public function it_should_get_half_price_discount()
{
$cost = 50;

$order = new Order();

// It does not connect to database or any other service
$discounted = $order->discount(Order::DISCOUNT_HALF_PRICE, $cost);

$this->assertEquals(25, $discounted);
}

Answer Source

The main idea of mocking is to decouple the dependency. Unit tests shouldn't have any kind of dependency. Say your business logic connecting to database layer which in turn connects to database. Now you are writing a unit test to test your business logic. If you are not decoupling database base layer from business logic then your unit test will go and hit database, which should never happen. So what you should do is to inject the database dependency to business logic layer and when writing unit test mock that dependency.

Long story short you don't need mock always for unit tests but if any dependency then that should be mocked. If your test has any dependency (say database dependency, file dependency etc.) then your test is not unit test but integration test

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download