首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试自定义期望?

如何测试自定义期望?
EN

Stack Overflow用户
提问于 2015-12-04 18:06:52
回答 1查看 388关注 0票数 5

假设我想要一个自定义的testthat期望。例如,我正在测试许多对象,看看它们是否没有缺失值。写东西的testhat方法应该是这样的:

代码语言:javascript
复制
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))
}

我如何测试它是正确的?

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

代码语言:javascript
复制
test_that(
  "expect_no_nas passes when there are no NAs",
  {
    expect_no_nas(1:5)
  }
)

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

代码语言:javascript
复制
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中也不起作用。

代码语言:javascript
复制
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的测试。)

EN

回答 1

Stack Overflow用户

发布于 2015-12-04 18:40:08

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

代码语言:javascript
复制
test_that(
  "expect_no_nas fails when there are NAs",
  {
    expect_error(
      test_that(
        "failing test",
        {
          expect_no_nas(c(1, NA))
        }
      ) 
    )
  }
) 
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34085729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档