2017-07-23 22 views
1

如何忽略testthat单元测试中的类属性?R testthat:如何忽略预期结果中的类(错误“类不同”)

目前测试失败,因为不同类别的:

library(testthat) 

testthat("drinks taste good", { 

    values <- c("COFFEE", "TEA", "SOFT DRINK") 

    expected.values <- values 

    class(values) <- "myclass" 

    expect_equal(values, expected.values, check.attributes = FALSE) 
    # Error: `values` not equal to `expected.values`. 
    # target is myclass, current is character 

    # funny: Try it with switched variables causes a different error message 
    expect_equal(expected.values, values, check.attributes = FALSE) 
    # Error: `expected.values` not equal to `values`. 
    # Classes differ: character vs myclass 
}) 

编辑1:expect_equivalent(values, expected.values)不工作也不因为它忽略的属性,但不类(通过check.attributes = FALSE):

Error: `values` not equivalent to `expected.values`. 
target is myclass, current is character 
+1

那么你可以使用unclass。或者您将正确的类添加到预期值。 – Roland

+1

好问题。如果你使用'as.character(values)'测试运行。但对我来说,似乎'check.attributes'参数并不符合我的预期。 – Christoph

+0

@Roland'unclass'似乎是最简单的方法。如果您发布这个答案,我会接受它! –

回答

1

你不能忽略类,所以必须处理你的代码中的差异。 正如评论建议,在这种情况下,unclass()就足够了。

至于切换attirbutes,类是检查独立的属性,所以你不能关掉check.attributes参数。

另外,切换值的顺序时,有趣的行为来自内部方法分派:它使用compare.defaultmyclass值是第一和compare.character当字符向量是第一。