I want to test a function with expect_equal() from the testthat package in R that extracts information from a string separated by |
. I also want to test the case when the input string is empty. However, in this case I do not achieve the expected equality (see code snippet below). I get the error "Error: result
not equal to expected
.
Component “info2”: 'is.NA' value mismatch: 0 in current 1 in target". How to solve this?
library(stringr)
library(testthat)
# Function to be tested
fn_extract_info <- function(some_text) {
info1 <- unlist(
stringr::str_split(
some_text, "\\|"))[1]
info2 <- unlist(
stringr::str_split(
some_text, "\\|"))[2]
return(list(
info1 = info1,
info2 = info2
))
}
# Test function
fn_test_fn_extract_info <- function(some_text, expected) {
result <- fn_extract_info(some_text = some_text)
expect_equal(result, expected)
}
# Execution of test function with empty string
fn_test_fn_extract_info(
some_text = "",
expected = list(info1 = "",
info2 = "NA")
)
The function fn_extract_info() with an empty string as input produces:
$info1
[1] ""
$info2
[1] NA
Note that "NA"
is not the same as NA
. And also not all NA
values are created the same. If you are expecting a missing character value, you should run this instead
fn_test_fn_extract_info(
some_text = "",
expected = list(info1 = "",
info2 = NA_character_)
)
NA_character_
is the special typed version of NA
for character values.