REST Assured测试因NoSuchMethodError失败,请求Auth0令牌遇阻
解决Rest-Assured + TestNG中NoSuchMethodError及Auth0令牌生成问题
问题根源
你遇到的java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch是依赖版本冲突导致的:TestNG 6.8.7依赖的Hamcrest版本过旧,而Rest-Assured 5.3.0需要更高版本的Hamcrest类库,两者方法签名不匹配,引发了该错误。
解决方案
1. 修复依赖冲突
修改build.gradle的依赖配置,通过以下两种方式解决版本冲突:
方案A:升级TestNG版本
将TestNG升级到与Rest-Assured 5.3.0兼容的稳定版本(如7.8.0),新版TestNG依赖的Hamcrest版本与Rest-Assured匹配:
plugins { id 'java' } group 'org.example' version '1.0-SNAPSHOT' repositories { mavenCentral() } dependencies { testImplementation 'io.rest-assured:rest-assured:5.3.0' testImplementation 'org.testng:testng:7.8.0' // 升级TestNG到兼容版本 implementation 'com.googlecode.json-simple:json-simple:1.1.1' implementation 'io.rest-assured:json-schema-validator:5.3.0' implementation 'commons-io:commons-io:2.12.0' implementation 'io.jsonwebtoken:jjwt:0.7.0' } test { useTestNG() }
方案B:排除旧Hamcrest并添加兼容版本
若不想升级TestNG,可排除TestNG自带的旧Hamcrest依赖,手动添加Rest-Assured需要的版本:
plugins { id 'java' } group 'org.example' version '1.0-SNAPSHOT' repositories { mavenCentral() } dependencies { testImplementation 'io.rest-assured:rest-assured:5.3.0' testImplementation('org.testng:testng:6.8.7') { exclude group: 'org.hamcrest' // 排除TestNG自带的旧Hamcrest } testImplementation 'org.hamcrest:hamcrest:2.2' // 添加兼容版本的Hamcrest implementation 'com.googlecode.json-simple:json-simple:1.1.1' implementation 'io.rest-assured:json-schema-validator:5.3.0' implementation 'commons-io:commons-io:2.12.0' implementation 'io.jsonwebtoken:jjwt:0.7.0' } test { useTestNG() }
2. 优化Auth0请求代码
你的Auth0请求为application/x-www-form-urlencoded类型,使用formParam时Rest-Assured会自动设置正确的Content-Type,无需手动指定(若contentTypeAuth0不是ContentType.URLENC可能引发格式错误),调整后代码如下:
else if(Env.equalsIgnoreCase("Auth0")) { response = given(). cookie(cookie). formParam("client_id", client_id). formParam("client_secret", client_secret). formParam("grant_type", grantType). formParam("username", auth0Username). formParam("password", auth0Password). formParam("realm", realm). formParam("audience", audience). when(). post(auth0TokenURL). then(). statusCode(200). contentType(ContentType.JSON).extract().response(); catchResponse = response.jsonPath(); auth0AccessToken = catchResponse.get("access_token"); }
若需手动指定Content-Type,确保使用ContentType.URLENC而非自定义字符串。
验证步骤
- 执行
gradle clean test清理旧依赖并重新运行测试 - 检查是否仍存在
NoSuchMethodError - 确认Auth0请求能正常获取
access_token
内容的提问来源于stack exchange,提问作者Jimil Patel
相关产品推荐
相关产品推荐

