2017-07-25 48 views
0

我有一個方法,它創建一個json對象並返回字符串。 我想就這個功能的單元測試,但該方法返回一個字符串,像這樣:斯卡拉測試單元與JSON字符串

{"att1":"{\"scale\": 0, \"significand\": 10}","name":"john","lastname":"smith","job":"developper"} 

如果你複製粘貼此行成逗號,你沒有得到的字符串。而且我不能再使用JSON.parseFull(),因爲這不是一個String。我不希望我的方法直接返回一個jsonObject。

我用這種對象的創建我的JSON字符串

val objectMapper = new ObjectMapper() 
val myJson= objectMapper.createObjectNode() 
objectMapper.writeValueAsString(myJson) 

而且我用這個代碼,使我的單元測試:

class MyJsonTest extends FlatSpec { 

    "My method" should "generate a valid json" in { 

    val myJsonString = getMyJson() //method to test 

    // this is not a valid String but my method return this: 
    val correctJson = "{"att1":"{\"scale\": 0, \"significand\": 10}","name":"john","lastname":"smith","job":"developper"}" 

    assert(correctJson === myJsonString) 

    } 

你有什麼想法?

+0

我會說創建的json是無效的,因爲結果字符串不應包含轉義字符'\'。 使用原始字符串驗證json很簡單,因爲您不必使用轉義字符,並且可以執行完全匹配字符串 「」「{」attr1「:{」scale「:0,」significant「:10},」name「:」John「}」「」 –

回答

1

你應該使用的「」「YOUR_STRING這裏‘’」,採取在考慮你的插值字符串你的「

class test extends FlatSpec { 

    def getSampleJson = """{"att1":"{"scale": 0, "significand": 10}","name":"john","lastname":"smith","job":"developper"}""" 

    "My method" should "generate a valid json" in { 

    val myJsonString = getSampleJson 

    // this is not a valid String but my method return this: 
    val correctJson = 
     s"""{"att1":"{\"scale\": 0, \"significand\": 10}","name":"john","lastname":"smith","job":"developper"}""" 


    println(myJsonString) // {"att1":"{"scale": 0, "significand": 10}","name":"john","lastname":"smith","job":"developper"} 

    println(correctJson) // {"att1":"{"scale": 0, "significand": 10}","name":"john","lastname":"smith","job":"developper"} 

    assert(correctJson === myJsonString) 

    } 
} 

所以,現在,你可以打電話給你的方法的getJSON :)

+0

不錯,但是,h你會調用myMethodToTest(),因爲:s「」「myMethodToTest()」「」返回字符串:myMethodToTest() –

+0

不,只要做val myJsonString = myMethodToTest() 沒有引號&它我會工作:) – elarib

+0

它不工作,因爲s「」「刪除斜槓,所以我沒有相同的字符串。例如: {「att1」:「{」scale「:0,」significantand「:10}」,「name」:「john」,「lastname」:「smith」,「job」:「developper」 } –