2013-11-08 3 views
0

В SOAPUI JsonSlurper возвращает null, даже если данные json являются правильными. Ниже приведено jsonObj. null. Это из-за длительных данных или чего-то другого. Я проверил свой формат данных и его правильность.SOAPUI, JsonSlurper возвращает null, даже если данные json являются правильными

import groovy.json.JsonSlurper 
def jsonObj = new JsonSlurper().parseText(messageExchange.response.contentAsString) 
+0

Такая же проблема :-( ли SoapUI просто использовать издеваться? Я попытался положить заводной-all.jar в JRE в "Lib/внеш", но не радость. Вы используете Java 6? –

+0

Привет, я новичок в SoapUI, и я, несомненно, что-то пропустил, но мне интересно, почему вы не разбираете контекст. Ответ, например jsonObj = new JsonSlurper(). ParseText (context.Response)? –

ответ

0

Хорошо, так что нет. Это может быть связано с запуском SoapUI на Java 6 (он не будет работать с Java 7) или нет.

Следовательно, обходной путь.

примеров, найденные в Интернете, не обязательно полезны, потому что:

  • Они могут быть написаны людьми, не обязательно плавными с Groovy
  • примеров скрыть основную проблему: Объекты один получает от SoapUI кажется вести себя по-разному в разных контекстах, например в контекстах SOAP или REST фактические классы объектов разные, и хотя одни и те же вызовы метода могут быть выполнены, возвращаемые значения будут отличаться (вы получаете строку XML вместо строки JSON). Поскольку Groovy слабо типизирован и поощряет утиную печать, приведенные примеры могут оказаться неожиданными, а не сразу очевидными способами.
  • В примерах отсутствует регистрация и утверждения.

Говорят, здесь мы идем. Мы хотим получить значение «InquiryId», которое можно найти в ответе, который, как нам известно, представлен строкой JSON.

// Get projet associated to current "testRunner" by walking up the tree of objects  
// "testRunner" is probably a http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/support/AbstractTestCaseRunner.html  

def myProject = testRunner.testCase.testSuite.project 

// "myProject" is probably a http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/WsdlProject.html 
// Let's verify this! If we have guessed wrongly, the script will fail 

assert myProject instanceof com.eviware.soapui.impl.wsdl.WsdlProject 

// Get the appropriate TestStep by walking down the tree of objects 
// It is recommended to use getXByName() throughout unless you want to 
// confuse yourself by using mixed accessor styles working only on some 
// classes that may appear in this expression: 

def myStep = myProject.getTestSuiteByName("Global test suite").getTestCaseByName("Test Case Foo").getTestStepByName("Create Inquiry") 

// The result is probably a http://www.soapui.org/apidocs/com/eviware/soapui/impl/wsdl/teststeps/WsdlTestStep.html 
// Let's verify this! If we have guessed wrongly, the script will fail 

assert myStep instanceof com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStep 

// Getting JSON string can be done like this. One can also do 
// 'otherStep.getPropertyValue("reponse") as String' 

def jsonString = otherStep.testRequest.response.contentAsString 

// Let's log what we got here:  

log.info "Returned JSON string is '${jsonString}'" 

// What we cannot do with the 'jsonString' is: 
// Give it to SoapUI's "XMLHolder" for parsing, because, in spite of people 
// saying so, it does not seem to understand JSON. 
// Give it to JsonSlurper because JsonSlurper returns null 
// So we extract the value by scanning the String directly using a regular 
// expression. See http://groovy.codehaus.org/Regular+Expressions 
// The pattern say: Look for something that starts with 
// {"InquiryId":" 
// and ends with 
// "} 
// and grab the characters between these endings. 
// We then look for "anywhere in the passed String" for the above using "find()" 
// rather than "match()" which would demand precise matching of the whole String. 

def pattern = ~/\{"InquiryId":"(.+?)"\}/  
def matcher = pattern.matcher(jsonString) 

if (matcher.find()) {  
    def inqId = matcher.group(1)  
    log.info "Returned string is '${inqId}'" 
    // We are done here 
    return inqId  
}  
else {  
    throw new IllegalArgumentException("Could not extract InquiryId from '$jsonString'")  
} 
Смежные вопросы