2017-07-23 20 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當字符向量是第一。