如何测试自定义期望?

时间:2015-12-04 10:06:52

标签: r testthat

假设我想要一个自定义testthat期望。例如,我测试了很多对象,看它们是否没有缺失值。编写事物的testhat方式应该是这样的:

expect_no_nas <- function(object, info = NULL, label = NULL)
{
  lab <- testthat:::make_label(object, label)
  expect(has_no_nas(object), sprintf("%s has nulls.", lab), 
    info = info)
  invisible(object)
}

has_no_nas <- function()
{
  !any(is.na(x))
}

我如何测试那是对的?

我可以编写通过的测试,没问题。

test_that(
  "expect_no_nas passes when there are no NAs",
  {
    expect_no_nas(1:5)
  }
)

我以为我可以在expect_error中包含自定义期望,但这不起作用:

test_that(
  "expect_no_nas fails when there are NAs",
  {
    expect_error(expect_no_nas(c(1, NA)))
  }
)   
## Error: Test failed: 'expect_no_nas fails when there are NAs'
## * Not expected: c(1, NA) has NAs.
## * Not expected: expect_no_nas(c(1, NA)) code raised an error.

将其包裹在try中也无效。

test_that(
  "expect_no_nas fails when there are NAs",
  {
    res <- try(expect_no_nas(c(1, NA)))
    expect_false(res$passed)
  }
) 
## Error: Test failed: 'expect_no_nas fails when there are NAs'
## Not expected: c(1, NA) has NAs.    

如何测试失败案例? (要记住的重要一点是,我们正在测试expect_no_nas是否有效,而不仅仅是编写使用expect_no_nas的测试。)

1 个答案:

答案 0 :(得分:5)

Nico的查询有助于澄清事情:你需要在测试中进行测试。

test_that(
  "expect_no_nas fails when there are NAs",
  {
    expect_error(
      test_that(
        "failing test",
        {
          expect_no_nas(c(1, NA))
        }
      ) 
    )
  }
)