Java 测试失败时的放心异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19390295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:44:44  来源:igfitidea点击:

Rest Assured Exception when test fails

javarestgroovyrest-assured

提问by user2884037

I have a simple rest-assured test that is verifying this json comes be with the correct data for a call. I am using rest-assured 1.8 and did swap the groovy jars for the groovy-all jar due to a known issue with 2 different versions of ASM.

我有一个简单的放心测试,用于验证此 json 是否带有正确的呼叫数据。由于 2 个不同版本的 ASM 的已知问题,我使用的是放心的 1.8 并且确实将 groovy jar 换成了 groovy-all jar。

My json the comes back looks like this:

我的 json 返回如下所示:

{"account":"12345"}

My code looks like this:

我的代码如下所示:

package com.blah.tests;

import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class AccountsTest {

public AccountsTest() {
}


@Test
public void getLocationAccount() {

            given().
                param("thingAccountIsfor","ABCD").
            expect().
                statusCode(200).
                body("account",equalTo("10")).
            when().
                get("http://machine:2343/rest/accounts/getaccount");

    }

}

When I run this matching the value i expect for the account it works fine. When I put in a value that does not match I get a stack trace:

当我运行这个匹配我期望的帐户值时,它工作正常。当我输入一个不匹配的值时,我会得到一个堆栈跟踪:

log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.SingleClientConnManager).
log4j:WARN Please initialize the log4j system properly.

java.lang.AssertionError: 1 expectation failed.
JSON path account doesn't match.
Expected: 10
  Actual: 12345

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
    at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:71)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:81)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:57)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:182)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:190)
    at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:399)
    at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.jayway.restassured.internal.RequestSpecificationImpl.invokeFilterChain(RequestSpecificationImpl.groovy:759)
    at com.jayway.restassured.internal.RequestSpecificationImpl$invokeFilterChain.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149)
    at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1142)
    at com.jayway.restassured.internal.RequestSpecificationImpl.this$applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy)
    at com.jayway.restassured.internal.RequestSpecificationImpl$this$applyPathParamsAndSendRequest.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149)
    at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:131)
    at com.jayway.restassured.specification.RequestSender$get.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
    at com.jayway.restassured.internal.ResponseSpecificationImpl.get(ResponseSpecificationImpl.groovy:226)
    at com.tim.tests.AccountsTest.getLocationAccount(AccountsTest.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access
Response res = given().
    param("thingAccountIsfor","ABCD").       
    when().
    get("http://machine:2343/rest/accounts/getaccount");
JsonPath jp = new JsonPath(res.asString());
String account = jp.get("account").toString();
0(ParentRunner.java:50) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.junit.runner.JUnitCore.run(JUnitCore.java:157) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) Process finished with exit code 255

I am running this inside Intellij. I did try to move the groovy jars, back in, move the conflicting version of the ASM off of my class path and re-run it. I got the same result so I don't beleive this has to do with using the groovy-all jar instead of the groovy jars that ship with rest-assured 1.8.

我在 Intellij 中运行它。我确实尝试将 groovy jars 移回,将冲突的 ASM 版本移出我的类路径并重新运行它。我得到了相同的结果,所以我不相信这与使用 groovy-all jar 而不是带有 rest-assured 1.8 的 groovy jar 有关系。

Does rest-assured throw an exception every time it has a test fail or is something wrong here?

每次测试失败或这里有什么问题时,rest-assured 是否都会抛出异常?

回答by dileepvarma

Yes, it will fail by throwing AssertionException. You have two ways to avoid this:

是的,它会通过 throw 失败AssertionException。您有两种方法可以避免这种情况:

  1. Catch the exception with AssertionError.
  2. Remove expect().statusCode().body()part and assign response to Response object and continue with desired tests by parsing it using JsonPathobject as below.

    Response res = given().
        param("thingAccountIsfor","ABCD").       
        when().
        get("http://machine:2343/rest/accounts/getaccount");
    JsonPath jp = new JsonPath(res.asString());
    String account = jp.get("account").toString();
    
  1. 用 捕获异常AssertionError
  2. 删除expect().statusCode().body()部分并将响应分配给 Response 对象,然后通过使用JsonPath对象解析它来继续进行所需的测试,如下所示。

      Response response = given().contentType("application/json")
                     param("thingAccountIsfor","ABCD").     
                    .get("url")
                    .then()
                    .assertThat()
                    .statusCode(200).and()
                    .body("$", notNullValue())
                    .extract().response();
      final JSONObject content = new JSONObject(response.getBody().asString());
      String val=content.getString("account");
    

回答by Abdullah Al Noman

##代码##

cleaner option

清洁选项