2014-03-04 33 views
0

當運行一個單元測試,我期待一個方法,我測試返回一個嵌套的數組是這樣的:測試嵌套列表是否符合預期的最佳方法是什麼?

[ 
{:identifier=>"a", :label=>"a label", 
    :sublist=>[{:identifier=>"sublist z", :label=>"z sublist label"}, {:identifier=>" sublist w", :label=>"sublist w label"}]}, 
{:identifier=>"b", :label=>"b label", 
    :sublist=>[{:identifier=>"sublist y", :label=>"y sublist label"}]}, 
..] 

什麼是最優雅的方式來檢查,如果返回的數組是我期望它是?

我正在使用Minitest規範,如果這有什麼區別。

順便說一句,元素的順序並不重要,可能會有所不同。

Thx。

+0

它只是可以重新排序的頂層元素(也就是'b'可以在'a'之前);或者子列表可以重新排序(這是'w'可以在'z'之前)? – Chowlett

+0

@Chowlett b可以在之前,w可以在z之前,並且:標識符可以在之前:label。 – vrepsys

+0

':identifier'和':label'無關緊要 - 無論如何,哈希都是無序的,所以無論「順序」如何,它們都會相等。嵌套列表的重新排序是棘手的... – Chowlett

回答

1

在這種情況下,爲minitest編寫custom matcher是理想的。 這裏是你需要在匹配器中添加的代碼。

def match_hash(h1, h2) 
    matched = false 
    h1.each do |ele| 
    h2.each do |ele2| 
     match_elements?(ele, ele2) ? (matched = true) : next 
    end 
    if !matched 
     return matched 
    end 
    end 
    matched 
end 

def match_elements?(ele, ele2) 
    if (ele[:identifier] != ele2[:identifier]) || (ele[:label] != ele2[:label]) 
    return false 
    end 
    if ele.has_key?(:sublist) && ele2.has_key?(:sublist) 
    return match_hash(ele[:sublist], ele2[:sublist]) 
    end 
    true 
end 

編寫自定義匹配using this example 然後使用match_hash在你的測試用例兩個散列進行比較。

注意:上面的代碼已經在irb中測試過,並且工作正常。

+0

thx我會稍後接受,當我有一個時刻來測試它 – vrepsys

+0

@vrepsys沒問題。如果您遇到代碼中的任何問題,請告知我。 –

相關問題