Chapter 7. Testing
Testing is a vital part of package development. It ensures that your code does what you want it to do. Testing, however, adds an additional step to your development workflow. The goal of this chapter is to show you how to make this task easier and more effective by doing formal automated testing using the testthat package.
Up until now, your workflow probably looked like this:
- Write a function.
- Load it with Ctrl/Cmd-Shift-L or
devtools::load_all()
. - Experiment with it in the console to see if it works.
- Rinse and repeat.
Although you are testing your code in this workflow, you’re only doing it informally. The problem with this approach is that when you come back to this code in three months’ time to add a new feature, you’ve probably forgotten some of the informal tests you ran the first time around. This makes it very easy to break code that used to work.
I started using automated tests because I discovered I was spending too much time refixing bugs that I’d already fixed before. While writing code or fixing bugs, I’d perform interactive tests to make sure the code worked. But I never had a system that could store those tests so I could rerun them as needed. I think that this is a common practice among R programmers. It’s not that you don’t test your code, it’s that you don’t automate your tests.
In this chapter, you’ll learn how to graduate from using informal ad hoc testing, done at the command line, to formal automated testing (aka unit testing). While ...
Get R Packages now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.