簡體   English   中英

testthat:立即預期錯誤和變量值?

[英]testthat: Expect error and variable value at once?

我想測試一個可能引發錯誤的函數,但我也想確保變量值正確(以驗證錯誤之前預期的最后狀態-因此我想測試有害的副作用)。 是否有可能做到這一點?

待測試的簡化表達

x <- 1    # could also be made "global" by "<<-"
stop("damn, an error occured")

我該怎么做

testthat("double check",
  expect_error_and_TRUE( x == 1, {
                                   x <- 1
                                   stop("damn, an error occured")
                                 }))

我找不到“ expect函數的“堆棧”(管道)方法?

如果一個函數返回一個值,它不會拋出錯誤,否則會舍入。 您可以根據需要在Expect_error中測試特定的字符串,因此可以在錯誤中設置x的值。

{
    x <- 1
    stop("damn, an error occured")
}
## Error: damn, an error occured
x
## [1] 1
rm(x)
f <- function(){
    x <- 1
    stop("damn, an error occured")
}
f() == 1
## Error in f() : damn, an error occured
expect_error(f(), "damn, an error occured")

f <- function(){
    x <- 1
    stop("damn, an error occured, x is ", x)
}
expect_error(f(), "x is 1")

我建議不要在函數外部測試代碼,因為它取決於運行它的環境,因此,如果在測試文件中運行它,則可能與代碼的“主要”部分不同

現在,這是一個更好的示例,用於測試有害副作用-以及一個簡單的解決方案:

library(testthat)

counter <- 1

test_that("error occurs but does not change the previous value", {

  expect_error(if (log("a") == 42) counter <- counter + 1)
  expect_equal(counter, 1)

})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM