
項(xiàng)目中的某個(gè)接口必須先登錄后調(diào)用,但是 header 中的Authorization 需要在登錄返回的token中添加一個(gè)字串,所以需要先獲得 token 并修改后傳遞給該接口的請(qǐng)求。
雖然這是常見(jiàn)的關(guān)聯(lián)的問(wèn)題,但是由于剛開(kāi)始研究gatling, 苦于中文相關(guān)文檔有限,看了官方文檔,也是有些茫然,嘗試了不同的方法后,終于看到請(qǐng)求成功了。
package advisorApp
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
class application extends Simulation {
val httpConf = http
.baseURL("https://xxxx.xxxx") // Here is the root for all relative URLs
.acceptHeader("application/json, text/plain, */*") // Here are the common headers
.acceptLanguageHeader("zh-CN,zh;q=0.9,en;q=0.8")
.acceptEncodingHeader("gzip, deflate, br")
.userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36")
val headers_10 = Map("Content-Type" -> "application/json") // Note the headers specific to a given request
val scn = scenario("SigningAdvisor")
.exec(http("login")
.post("/advisor-auth/api/auth/xxxx/_actions/loginOrRegisterUser") //test data
.headers(headers_10)
.body(StringBody("""{ "phone": "177xxxxxxxx","verificationCode":"7777"}""")).asJSON
.check(status.is(200))
.check(jsonPath("$..userId").saveAs("userId"))
.check(jsonPath("$..token").exists)
.check(jsonPath("$..token").saveAs("token"))
)
// 取出 token 值并修改
.exec(session => {
val token = session("token").as[String]
val token2 = "Bearer " + token
session.set("token",token2)
})
// 打印 session 驗(yàn)證正確性
.exec { session => println(session)
session
}
.exec(http("advisorSigning")
.post("/bms-advisor/api/advisors")
.headers(headers_10)
.header("Authorization","${token}")
.body(StringBody("""{"userId": "5a5d9d1f30c49e0008c1c913",
"advisorPhone": "xxxxxx", //? test data
"emailAddress": "Q@123.com",
"advisorName": "xxxx", //test data
"idCardNumber": "xxxxxxx", //test data
"nation": "Han",
"highestDegree": "doctor",
"politicalStatus": "ptgm",
"provinceCompanyId": "59f422cdb2b14f0008a1166d"}""")).asJSON)
setUp(scn.inject(atOnceUsers(1)).protocols(httpConf))
}
打印出的session 結(jié)果:
Session(SigningAdvisor,1,Map(gatling.http.cache.dns -> io.gatling.http.resolver.ShuffleJdkNameResolver@54fba1c8, userId -> 5a5daee230c49e0008c1c915, token -> Bearer eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiI1YTVkYWVlMjMwYzQ5ZTAwMDhjMWM5MTUiLCJkYXRhIjoiMzI5MDQyNDQtZTUwZC00ZmExLWIyMWYtY2MxNjM3ZTZlOGI3IiwiZXhwIjoxNTE2Njk2MDc3fQ.yJsKzVk1wkT4j6Ygdua4jpoxq1V3zzXZ8hDuk3EI4Pw),1516091277053,151,OK,List(),io.gatling.core.protocol.ProtocolComponentsRegistry$$Lambda$409/115086468@687d0e8a)