Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple expectations with test_that

Is there a way to have multiple for expections for an expect_that unit test? For instance, for a given expect_that() statement, I'd like to expect that the function f() gives a warning and also returns the number 10.

like image 214
andrew Avatar asked Sep 12 '25 19:09

andrew


2 Answers

context("Checking blah")

test_that("blah works",{
    f <- function(){warning("blah"); return(10)}
    expect_warning(x <- f())
    expect_equal(x, 10)
})

You can save the output while checking for the warning. After that check that the output is what you expect.

like image 120
Dason Avatar answered Sep 15 '25 10:09

Dason


test_that("f works as expected", {
expect_warning(f())
expect_equal(f(), 10)
}
)

If I understand your context correctly, this should work. The test would fail and report if either or both of the expectations weren't met.

To run the function only once, you could try wrapping the function within the test_that:

    test_that("f works as expected", {
a <- tryCatch(f(), warning=function(w) return(list(f(), w)))
expect_equal(a[[2]], "warning text")
expect_equal(a[[1]], 10)
rm(a)
}
)

I haven't tested this so I'm not sure if it'll work in your particular case, but I've used similar approaches with test_that in the past.

like image 34
Nan Avatar answered Sep 15 '25 10:09

Nan