假设我想要一个自定义的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的测试。)
发布于 2015-12-04 18:40:08
Nico的查询有助于澄清这一点:您需要在测试中进行测试。
test_that(
"expect_no_nas fails when there are NAs",
{
expect_error(
test_that(
"failing test",
{
expect_no_nas(c(1, NA))
}
)
)
}
) https://stackoverflow.com/questions/34085729
复制相似问题