My testing epiphany
Peter Bryant
Posted on April 11, 2018
I've been making apps for about 2 years, and in that time I never understood the community's obsession with unit testing. I figured that if I can run the app and see it working, what's the point in taking loads of time to write automated tests?
The answer revealed itself to me recently.
You don't write tests to make sure your code works now: you write tests so that you can spot your code breaking in the future.
Here's an example. We've written a file in RotaCloud for Android which contains a bunch of functions for working with time. Here's our method for formatting a timestamp - in seconds - as a 24-hour time:
fun Long.secondsToTime() {
return SimpleDateFormat("HH:mm", Locale.UK)
.format(this * 1000)
}
This function is pretty important to our app: if it breaks, suddenly everyone's rotas will be displaying incorrect information.
So what happens when a dev unwittingly changes this function like this?
fun Long.secondsToTime() {
return SimpleDateFormat("HH:mm", Locale.UK)
.format(this * 100)
}
This change will not cause a crash in the app, but it will mean that the whole system is pretty useless, and our users will not be happy.
So we wrote a test:
@Test
fun secondsToTimeTest() {
val timeInSeconds = 1523451825
val expectedTime = "13:03"
assertEquals(expectedTime, timeInSeconds.secondsToTime())
}
This is a really simple test, but running it before a new release ensures that this vital functionality keeps working.
We can extend these tests to cover some other requirements too e.g. the hour should always be two digits: 09:30
is correct, but 9:30
isn't.
So that was my testing epiphany. It's pretty easy to manually determine whether or not something works, just by looking at it. What automated tests do, however, is ensure that all the app's functionality continues to work in the future, without you having to manually look through the whole thing.
Testing is also incredibly useful for collaborative development: simply require everyone to run the test suite before submitting a pull request, and you'll find yourself having to deal with a lot fewer broken implementations.
Posted on April 11, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024