Тест JUnit для Post Rest WS с использованием rest-assured - PullRequest
0 голосов
/ 19 января 2019

Я пишу junit для post, используя rest-assured и при выполнении

Мой тестовый класс:

public class PolicyResourceTest {

    private static MockRESTServer server;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        server = new MockRESTServer(8080, new PolicyResource());
        server.start();
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        server.stop();
    }

    @Test
    public final void testCreatePolicy() {
        Policy policy=new Policy();
        policy.setName("policy123");

         RestAssured.with()
                .contentType("application/json")
                .accept("application/json")
                .body(policy)
                .post("/create")
                .then()
                .assertThat()
                .statusCode(200);   
    }

Мой класс ресурсов:

@Path("/")
public class PolicyResource {
     @POST
     @Path("/create")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     public Response test( Policy messageBody) {
        System.out.println("policy: "+messageBody);
        return Response.ok().status(200).build();    
     }
}

Я получаю ниже исключения:

org.apache.http.NoHttpResponseException: localhost:8080 failed to respond
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:281)
    at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:257)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:207)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:684)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.HttpClient$execute$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at io.restassured.internal.RequestSpecificationImpl$RestAssuredHttpBuilder.doRequest(RequestSpecificationImpl.groovy:2028)
    at io.restassured.internal.http.HTTPBuilder.post(HTTPBuilder.java:349)
    at io.restassured.internal.http.HTTPBuilder$post$2.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at io.restassured.internal.RequestSpecificationImpl.sendRequest(RequestSpecificationImpl.groovy:1202)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)

1 Ответ

0 голосов
/ 27 марта 2019

@ Анжу Сингх, убедитесь, что ваш бэкэнд работает нормально.

Я попробовал запрос на своем локальном компьютере, как и на макете API, и также смог успешно протестировать объекты.Исключение, которое вы получили org.apache.http.NoHttpResponseException: localhost: 8080 не удалось ответить, с сервера.Нет проблем от RestAssured или JUnit для решения.

@Test(enabled=true)
    public void sampleTester() {

        EnrollEmail email = new EnrollEmail();
        email.setEmailAddress("sample@domain.com");
        RestAssured.given().contentType(ContentType.JSON).body(email).when().post("https://jsonplaceholder.typicode.com/posts").then()
        .assertThat()
        .statusCode(201);  

    }

    @Test(enabled=true)
    public void sampleTester2() {

        EnrollEmail email = new EnrollEmail();
        email.setEmailAddress("sample@domain.com");
        RestAssured.given().contentType(ContentType.JSON).body(email).when().post("http://localhost:8089/posts").then()
        .assertThat()
        .statusCode(201);  

    }
...