如何在testthat框架中设置expect_equal的容差

时间:2014-08-23 15:25:41

标签: r unit-testing testthat

我想知道是否可以在R中使用testthat测试框架来设置相等的容差。

目前,如果example.R是:

library(testthat)
three_times<-function(x) 3*x

context('Test three_times')
test_that('Three times returns 3 times x',{
    expect_equal(three_times(3),9)
    expect_equal(three_times(pi),9.4247)
})

并使用test_file('example.R','stop')执行,第一个测试通过,但第二个测试失败:

 Error: Test failed: 'Three times returns 3 times x'
Not expected: three_times(pi) not equal to 9.4247
Mean relative difference: 8.271963e-06. 

是否可以为平均相对差异设置更高的误差阈值?例如1e-3。我有一些只有3位小数精度的预期结果,这意味着现在我的测试总是失败......

1 个答案:

答案 0 :(得分:25)

您可以传递参数scaletolerance。这些参数传递给all.equal

expect_equal(three_times(pi),9.4247, tolerance=1e-8)
Error: three_times(pi) not equal to 9.4247
Mean relative difference: 8.271963e-06

expect_equal(three_times(pi),9.4247, tolerance=1e-3)

有关更多帮助,请参阅?all.equal