Question
- **7c.**(0.4 point) Now for a bit of unit testing. Download and install the `testthat` package if you haven't already. We'll use the `test_that()` function.
- **7c.**(0.4 point) Now for a bit of unit testing. Download and install the `testthat` package if you haven't already. We'll use the `test_that()` function. It works as follows. Each call we make to `test_that()` has two arguments: the first is message that describes what we are testing, and the second is a block of code that evaluates to TRUE or FALSE. Typically the block of code will use `expect_true()` or `expect_error()`, in the last line. The structure is thus:
```
test_that("Message specifying what we're testing", {
code goes here
code goes here
expect_true(code goes here)
})
```
If the output of your code is TRUE (the test passes), then the call to `test_that()` will show nothing; if the output of your code is FALSE (the test fails), then we'll get an error message signifying this. Here is an example for checking that the function from Q2a works for `n=3`:
```{r}
library(testthat)
test_that("add.up.inv.powers() works for n=3", {
res = add.up.inv.powers(n=3, verb=FALSE)
expect_true(res==(1 + 2^(1/2) + 3^(1/3)))
})
```
And another example for checking that the function from Q2a fails for non-integer inputs:
```{r}
test_that("add.up.inv.powers() fails for non-integer n", {
expect_error(add.up.inv.powers(n="c", verb=FALSE))
})
```
Neither of these calls to `test_that()` produced any messages, which means that tests executed as we expected.
Now implement your own unit tests for `sentence.flipper()` from Q3c. Write several tests, checking that it flips simple sentences as you'd expect, that it returns a vector of strings when it's passed a vector of strings, and that its output vector has the same length as the input vector.
```{r}
test_that("sentence.flipper() flips simple sentences as you'd expect", {
expect_equal(sentence.flipper("the quick brown fox jumped over the lazy dog"), "eht kciuq nworb xof depmuj revo eht yzal god")
})
test_that("that sentence.flipper() output vector has the same length as the input vector", {
expect_equal(sentence.flipper(length("the quick brown fox jumped over the lazy dog")), 1)
})
```
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started