【问题标题】:How do you test a custom expectation?如何测试自定义期望?
【发布时间】:2016-08-10 19:56:47
【问题描述】:

假设我想要一个自定义的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 的测试。)

【问题讨论】:

  • 我有点困惑...您的预期输出是什么?当存在 NA 时,该函数会出错......正如它应该的那样,或者我误解了你想要做什么?
  • 是的,expect_no_nas 应该在有 NA 时给出错误。但由于我想测试expect_no_nas 函数,我想要一个元测试。也就是说,测试expect_no_nas 正确失败的(通过)测试。再读一遍,我明白你为什么感到困惑了。
  • 好的,现在我明白你的意思了!

标签: r testthat


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2012-06-06
    • 2020-06-26
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多