Mocking in Unit Tests

May 13, 2024 note-to-self

In testing a specific class, you mock it's dependencies to make sure that class calls the dependency correctly.

Mock the dependency.

  • shouldReceive - declare what should be called
  • times(x) - declare how many times it should be called
  • with - declare what the arguments should be.

New-up the class under-test and call the public method as per normal. Because of the mocked dependency set up, you should be able to tell if the mocked dependency was called correctly. In other words, in this test, you don't care if the mocked-class works well, just that the calling-class called it properly.

A separate test would determine whether the mocked-class works well.

Not only should the unit test check that class-under-test calls the correctly method (shouldReceive) the correct number of times, but also with the correct inputs (with) based on what was pass to the class-under-test.

$underTest = new classUnderTest($mockedClass)
$underTest->handle('foo', 'bar');

Those arguments should be passed to the mocked class correctly.