Thursday, 10 August 2017

Learning about unit testing...

Good info from Steph yesterday at our R-User Group.

1.   Create an R script in the test folder.
Q: do they have to start with "test-"?

2.   Add a context using the context() function.
Gives information about what's been tested and why in broad terms.

3.   Key function is test_that()
The test_that() function has two arguments:
A. description - test name.
B. test code made up of expectation - in curly brackets


Code for my first simplest tests:

test_that("extract_names gives a list",{

  # load data from the package - should I move it into the test folder
  data("protein_json")
  # creates object protein_json in the environment.
  # it's the json data for Q04206 - for the transcription factor RelA

  # Nice simple test
  res <- extract_names(protein_json)
  expect_is(res, "list")
  expect_equal(length(res),6)

})

To run the tests 

- operate within the Rproj for your package.

Use the function: test()


When it doesn't work, output looks like this:


> test()
Loading drawProteins
Testing drawProteins
extract_names: 1

Failed ----------------------------------------------------------------------
1. Error: extract_names gives a list (@test-extract_names.R#12) -------------
object 'sample_protein_json' not found
1: extract_names(sample_protein_json) at /Users/paulbrennan/Documents/drawProteins/tests/testthat/test-extract_names.R:12

DONE ========================================================================

When it works it looks like this:

> test()
Loading drawProteins
Testing drawProteins
extract_names: ..

DONE ========================================================================


That's enough for now...

No comments:

Post a Comment