```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Introduction

Up until now, your workflow probably looks like this:

1. Write a function.
2. Load it with or `devtools::load_all()`.
3. Experiment with it in the console to see if it works.
4. Go back to 1.

While this is testing, sometimes a more formal approach is better. 

Let's start by setting up our package to use the `testthat`: `usethis::use_testthat()`. 

# Unit tests

Advantages: 

1. Better code, you are explicit about how the code behaves
2. Better structure, many small components working together
3. Easier to start up, all your tests are documented in a script
4. Fearless development, don't have to worry about unknowingly breaking something

Unit tests with `testthat` are defined in terms of expectations. The package provides a suite for functions that have the `expect_` prefix that compare the values of different objects: 


```{r, error = TRUE}
library(testthat)
expect_equal(1, 1 + 1)
expect_lt(1, 1 + 1)

```

General principles: 

1. When you are tempted to write a "print" statement, write a test instead. 
2. Write tests for complex code with lots of interdependencies
3. Write a test when you discover a bug.

# Example

- What bug did we discover in the sampling function? 
- What is the expected behavior in this case and how does it fail?
- Let's write a test!


# Organizing tests

# Alternatives

- You don't have to use `testthat`

# `devtools::check()`

- CRAN automatically runs the code in the `tests` subdirectory
- If they fail, you will be notified. 
- CRAN does other things as part of check! Let's review them. 


