Testing Top-Level Functions

Top-level functions

The Airport class we designed using tests has the facility to return the information about a single airport and to sort a list of airports by name. We need a function that will take a list of airport codes and return a sorted list of airport information. We’ll implement that function in a new AirportStatus.kt file, as a top-level function rather than as a method of a class. It turns out testing a top-level function isn’t any different than testing a method of a class, as we’ll see soon.

Test for returning a list

In the spirit of growing code incrementally using tests, let’s first implement a simple, synchronous version of a getAirportStatus() function that takes a list of airport codes and returns a sorted list of Airport instances filled with information about each relevant airport. Let’s look at the test first.

We’ll use the first test to tease out the signature of the method getAirportStatus()—it should take a list of airport codes and return a list of Airports. Very quickly we’ll need a few more tests for different combinations of airport codes. When writing the first test, we’ll prepare for that by writing a data-driven test. Let’s create a file named AirportStatusTest.kt under the src/test/kotlin/com/agiledevelop- er/airportstatus directory with the following code:

Get hands-on with 1400+ tech skills courses.