当前位置:  开发笔记 > 编程语言 > 正文

你如何测试自定义的期望?

如何解决《你如何测试自定义的期望?》经验,为你挑选了1个好方法。

假设我想要一个自定义的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> Richie Cotto..:

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

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

推荐阅读
U友50081205_653
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有