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
.
Asked
Active
Viewed 1,236 times
3

andrew
- 2,524
- 2
- 24
- 36
2 Answers
2
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.

Nan
- 446
- 4
- 14
-
`f()` takes about 10 minutes to run, so I'm looking for a way to test both outcomes (equal to 10 and gives warning) with out having to run `f()` twice. – andrew Apr 30 '14 at 19:56
-
This is still calling `f()` twice though – andrew Apr 30 '14 at 21:04
-
No it isn't. f() is called and the output assigned to a. Then a is called for the tests – Nan Apr 30 '14 at 21:14
-
I guess I mean in the event that a warning is given, it looks like f() will be called twice. – andrew May 01 '14 at 14:04
-
I think you are correct. Try following the answers here: http://stackoverflow.com/questions/3903157/how-can-i-check-whether-a-function-call-results-in-a-warning – Nan May 01 '14 at 16:18
2
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.

Dason
- 60,663
- 9
- 131
- 148
-
1Can you explain why `x` is available outside `expect_warning`? I would've thought that `x <- f()` would be executed within the context of `expect_warning`, and that the `x` would not be available to pass to the subsequent `expect_equal` function. Additionally, what if it is not as easy as saving the output of `f()`? For instance, if I wanted confirm that neither warnings nor errors were thrown. – andrew Apr 30 '14 at 21:10