在 Groovy、Spock 和 Rest Assured 测试中使用三元运算符 - 集成测试

问题描述 投票:0回答:2

我有下面的代码,我想根据测试的

where
部分替换值:

void 'should pass some test() {
  given:
  stubFor(get(urlEqualTo("/someVal/$productOrderId"))
     .willReturn(defaultWiremockResponse()
       .withBody(""" 
          {
            "startDateTime" : ${myTime? "$myTime" : null}
          }
       """
    )
   //...... some when
   //...... some then
   where:
   productOrderId | myTime
   "1"            | "2023-04-23T07:13:15.862Z"  
   "2"            | "null" 
}

此测试适用于

null
,但会给出像
"2023-04-23T07:13:15.862Z"

这样的值的错误

嵌套的异常是 com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('-' (code 45)): was expecting comma to separate Object entries

我认为

"startDateTime"
没有得到双引号包裹的价值
""
并得到如下

{
  "startDateTime" : 2023-04-23T07:13:15.862Z   // missing quotes around the value
}

这可能就是问题所在。有人可以帮助我理解这一点并修复此错误以进行字符串插值

java testing groovy spock wiremock
2个回答
0
投票

尝试使用

\
来处理双引号

"startDateTime" : ${myTime? "\"${myTime}\"" : null}

0
投票

就像我在 Shashank Vivek 的回答下的评论中所说,你也可以这样做,完全避免嵌套的 GString 插值:

class MySpec extends Specification {
  def 'should pass some test'() {
    given:
    println \
      """\
      {
        "startDateTime" : ${myTime? '"' + myTime + '"' : null}
      }\
      """.stripIndent()

    expect: true
   
    where:
    productOrderId | myTime
    "1"            | "2023-04-23T07:13:15.862Z"  
    "2"            | null
  }
}

控制台日志:

{
  "startDateTime" : "2023-04-23T07:13:15.862Z"
}    
{
  "startDateTime" : null
}

Groovy Web 控制台中尝试它。

随意忽略反斜杠和缩进删除。我只是在避免不必要的缩进和换行符。

© www.soinside.com 2019 - 2024. All rights reserved.