Я новичок в тестировании с Junit и использовании mockito. Я создал класс для своего клиента, который должен отправлять запросы в API. Я также создал класс для написания простого теста. Когда я запускаю тест, я получаю ошибки в консоли и не знаю, как их исправить. Я проверил API, к которому я отправляю запросы с помощью Почтальона.
Вот мой код для Клиента:
import io.netty.handler.codec.http.HttpResponse;
import io.vertx.core.AsyncResult;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
public class MyClient {
private WebClient webclient;
private String requestURL;
private static Logger logger = LoggerFactory.getLogger(MyClient.class);
public MyClient(WebClient webclient, String requestURL) {
this.webclient = webclient;
this.requestURL = requestURL;
}
public void invokeCore(JsonObject request, java.util.function.Consumer<JsonObject> func){
webclient.post(requestURL)
.putHeader("content-type", "application/json")
.sendJson(request, ar -> {
if (ar.succeeded()) {
logger.info("succeeded: " + ar.succeeded());
logger.info("statusCode: " + ar.result().statusCode());
logger.info("body: " + ar.result().body());
logger.info("headers: " + ar.result().headers());
JsonObject response = new JsonObject();
// populate it
func.accept(response);
} else {
logger.info("Executed: " + ar.cause());
}
});
}
}
Вот что я написал для тестового класса: я настроил фиктивный WebClient и использую его при создании экземпляра MyClient для отправки запроса в API.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.*;
import java.awt.List;
import javax.xml.ws.Response;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import io.netty.util.concurrent.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
@ExtendWith(VertxExtension.class)
public class MyClientTest {
private MyClient client;
//set up WebClient
private WebClient createMockWebClient(JsonObject mockResponse) {
WebClient mockWebClient = mock(WebClient.class);
HttpRequest<Buffer> mockRequest = mock(HttpRequest.class);
when(mockWebClient.post(any())).thenReturn(mockRequest);
when(mockRequest.putHeader(any(), any())).thenReturn(mockRequest);
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// TODO Auto-generated method stub
java.util.function.Consumer func = invocation.getArgument(1);
func.accept(mockResponse);
return null;
}
}).when(mockRequest).sendJson(any(), any());
return mockWebClient;
}
@Test
@DisplayName("Test response from client")
public void test() {
//request being sent
JsonObject request = new JsonObject().put("SSN", "123456789").put("Address", "123 main st").put("zip", "08888").put("dob", "012387");
//expected response
JsonObject response = new JsonObject().put("clientToken", "11oije311").put("clientID", "123ID");
//test setup
MyClient coreClient = new MyClient(createMockWebClient(new JsonObject()), "http://localhost:8080/core");
//test steps
coreClient.invokeCore(request, resp -> {
assertEquals(resp.getString("clientToken"), response.getString("clientToken"));
//end.finished();
});
}
}
Вот ошибка, которая появляется в консоли, когда я пытаюсь запустить тест:
А вот pom.xml для проекта:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company.projectname</groupId>
<artifactId>myprofile</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>myprofile</name>
<description>Service to retrieve my profile</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<vertx.version>3.6.0</vertx.version>
<junit-jupiter.version>5.1.0</junit-jupiter.version>
<assertj-core.version>3.8.0</assertj-core.version>
<vertx.verticle>com.company.projectname.myProfileVerticle</vertx.verticle>
</properties>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-junit5</artifactId>
<version>${vertx.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<!-- Vert.x Maven Plugin -->
<!-- Auto re-deploy on code change: "mvn clean vertx:run" -->
<!-- Warning!!! Starts detached process, must manually kill when done. -->
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>vertx-maven-plugin</artifactId>
<version>1.0.13</version>
<executions>
<execution>
<goals>
<goal>initialize</goal>
<goal>package</goal>
</goals>
</execution>
</executions>
<configuration>
<redeploy>true</redeploy>
</configuration>
</plugin>
<!-- Fabric8 Maven Plugin -->
<!-- Deploy to openshift or kubernetes: "mvn clean fabric8:deploy" -->
<!-- Note: See src/main/fabric8/deployment.yml for deployment config -->
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>fabric8-maven-plugin</artifactId>
<version>3.5.41</version>
<executions>
<execution>
<id>fabric8</id>
<goals>
<goal>resource</goal>
<goal>build</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<!-- Deploy to Nexus -->
<distributionManagement>
<repository>
<id>projectnamereleases</id>
<url>http://artifactory.company.local/artifactory/projectnameReleases/</url>
</repository>
<snapshotRepository>
<id>projectnamesnapshots</id>
<url>http://artifactory.company.local/artifactory/projectnameSnapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>