2016-10-12 6 views
0

JSONレスポンスでアサーションを実行するために、SOAPUIに次のgroovyスクリプトを記述しました。GroovyでJsonSlurperを使用してJSONパラメータを抽出する方法

Weather> main> CloudsプロパティとJSONレスポンスの価値について、アサーションを作成してアサーションするのが難しいです。

誰かが自分のコードを修正して、自分が望む価値を引き出すことを助けてくれますか?

ありがとうございます!

import groovy.json.JsonSlurper 

def json = '''{ 
"coord": { 
    "lon": -0.13, 
    "lat": 51.51 
    }, 
"weather": [ 
    { 
    "id": 801, 
    "main": "Clouds", 
    "description": "few clouds", 
    "icon": "02n" 
    } 
    ], 
"base": "stations", 
    "main": { 
    "temp": 281.644, 
    "pressure": 1027.43, 
    "humidity": 100, 
    "temp_min": 281.644, 
    "temp_max": 281.644, 
    "sea_level": 1035.14, 
    "grnd_level": 1027.43 
    }, 
    "wind": { 
    "speed": 3.33, 
    "deg": 43.5005 
}, 
"clouds": { 
    "all": 12 
}, 
"dt": 1476231232, 
    "sys": { 
    "message": 0.0084, 
    "country": "GB", 
    "sunrise": 1476253200, 
    "sunset": 1476292372 
}, 
    "id": 2643743, 
"name": "London", 
"cod": 200 
    }''' 


def result = new JsonSlurper().parseText(json) 
log.info(result) 
assert result.weather.main == "Clouds" 

答えて

0

天気は地図の配列です。したがって、アイテムを選択する必要があります。またはgroovyがmainの配列を返します。

assert result.weather.first().main == "Clouds" 
​assert result.weather.main == ["Clouds"​]​ 
0

これはちょっとした問題です。

weatherは配列([]内)であり、アサーションが失敗する理由です。

"weather": [ 
    { 
    "id": 801, 
    "main": "Clouds", 
    "description": "few clouds", 
    "icon": "02n" 
    } 
    ], 

あなたがresult.weather​.main​を行う場合、それは要素Cloudsを含むリストを返します。しかし、期待通りの価値はありません。あなたが行うことができますので、

、:

assert result.weather​[0].main == 'Clouds', 'Not matching the expected result'または
assert result.weather​.main == ['Clouds']または
assert result.weather.main.contains('Clouds')

天候が以下である場合と仮定するため(JSON配列内の複数の要素を持つ例):

"weather": [ 
    { 
    "id": 801, 
    "main": "Clouds", 
    "description": "few clouds", 
    "icon": "02n" 
    }, 
    { 
    "id": 802, 
    "main": "CloudApps", 
    "description": "few clouds", 
    "icon": "03n" 
    } 
    ], 

次にアサーションを行うことができます assert result.weather.main == ['Clouds', 'CloudApps']

0

jsonの天気は配列です。あなたは、通常の配列としてそれを

assert result.weather.main[0] == "Clouds" 
assert result?.weather?.main?.getAt(0) == "Clouds" 

二れる好ましいの要素にアクセスすることができ、それはnull安全

理由
関連する問題