2013-03-12 8 views
17

現在、私はSpring MVCプロジェクトの単体テストを書いています。 返されるメディアの種類がJSONであるため、jsonPathを使用して、正しい値が返されるかどうかを確認します。SpringMVC/mockMVC/jsonpathの比較文字列のリスト

問題は、文字列のリストに正しい(そして正しい)値が含まれているかどうかを確認することです。

マイプランでした:リストが返されることになっています各要素について正しい長

  • を持っていることを

    1. チェック、それがリストに悲しげに

    だかどうかを確認する、のいずれもこれらのことはうまくいくようです。

    はここに関連する私のコードの一部です:最初の2つだけ "期待"

    Collection<AuthorityRole> correctRoles = magicDataSource.getRoles(); 
    
    ResultActions actions = this.mockMvc.perform(get("/accounts/current/roles").accept(MediaType.APPLICATION_JSON)) 
    .andExpect(status().isOk()) // works 
    .andExpect(jsonPath("$.data.roles").isArray()) // works 
    .andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); // doesn't work 
    
    for (AuthorityRole role : correctRoles) // doesn't work 
        actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists()); 
    

    (ISOK &でIsArray)が働いています。他のもの(長さと内容について)私はねじれて回転することができますが、私は望む、彼らは私に何か有用な結果を与えていない。

    提案がありますか?

  • 答えて

    42

    1)の代わりに

    .andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); 
    

    を試みる代わり

    for (AuthorityRole role : correctRoles) // doesn't work 
        actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists()); 
    

    の)

    .andExpect((jsonPath("$.data.roles", Matchers.hasSize(size)))); 
    

    2を試みる

    actions.andExpect((jsonPath("$.data.roles", Matchers.containsInAnyOrder("role1", "role2", "role3")))); 
    

    hamcrest-libraryを追加する必要があることに注意してください。ここで

    +0

    ありがとうございました!それはたくさんの助けになりました! –

    +0

    助けがあれば、私の答えは受け入れられるとマークできます:) – chaldaean

    +0

    @chaldaeanどのhamcrestライブラリを使用していますか?私が持っているhamcrest-all-1.1では、org.hamcrest.MatchersクラスにhasSizeとcontainsInAnyOrderというメソッドは含まれていません。 –

    0

    は、私が使用して終了するものである:

    .andExpect(jsonPath('$.data.roles').value(Matchers.hasSize(size)))

    .andExpect(jsonPath('$.data.roles').value(Matchers.containsInAnyOrder("role1", "role2", "role3")))