PHPUnit — How to unit test a method with no return value?

Farhan Syed
2 min readFeb 18, 2021

When writing unit test for one public function in my class. I was a bit confused about how to test a function which has no return value(s). Normally unit tests validate return of boolean value, arrays or some object. There are parts of code which test of Exceptions being thrown from a function. In this scenario I was not throwing any exception or returning a value. What I wanted to test though if certain functionality was executed or not executed when function was being called.

Example code of a function returning void

Class UpdateShipmentTracking has the following things

1) It has a constructor injection of class Tracking.

2) It has a function called send which does not return anything. If array is not empty it updates the shipment tracking number.

How can we test a function like this, to be sure that it is functioning properly? If we observe the code properly there are 2 possibilities that can happen when the send function will be called.

Possibility 1
If we pass empty array to the function. Nothing will be executed. The track function of class Tracking will never be called.

Possibility 2
If we pass 1 element in the array. The track function of class Tracking will be called 1 time.

Now that we can see the possibilities. We can test the 2 scenarios. By doing so we cover that the function returning void is properly tested. If you do not believe my statement the screenshot of code coverage will prove that this is indeed true.

Unit Test

PHPUnit Code Coverage is 100%

Code Coverage

Happy Coding.

--

--