简体   繁体   English

对test_that的多重期望

[英]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 . 例如,对于给定的expect_that()语句,我希望函数f()给出警告并返回数字10

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中:

    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. 我尚未对此进行测试,因此不确定是否可以在您的特定情况下使用,但过去我在test_that中使用了类似的方法。

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. 之后,检查输出是否符合您的期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM