Am trying mockservice using mock server in karate.
My Moto : I have a feature file which calls third party api. If Api is down, I need to mock response. So that my tests will pass..
What I done : I created a feature file which calls Third party api (not localhost api). Am calling this feature file from java file. In the same java file written some code to mock the response
How am running code : Running the java file as Junit
Tried some ways but not working.Any guidance would be appreciated.
callApi.feature :
Feature: To test GET by mock service
Scenario: To test GET by mock service
Given url 'https://abcdefg.in/api/users/1' # ----> Fake api url to work like api is down
When method get
Then status 200
* print response
SimpleMockServerTest.java -- > This is the file which calls feature file and responsible for mocking the response.
package test.java.file;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.mock.Expectation;
import org.mockserver.model.Parameter;
import com.intuit.karate.Results;
import com.intuit.karate.Runner.Builder;
public class SimpleMockServerTest {
private static ClientAndServer mockServer;
@BeforeAll
public static void startMockServer() {
mockServer = startClientAndServer(9092);
String body = "{\r\n" + "\"id\": 7,\r\n" + "\"email\": \"michael.lawson@reqres.in\",\r\n"
+ "\"first_name\": \"Michael\",\r\n" + "\"last_name\": \"Lawson\",\r\n"
+ "\"avatar\": \"https://reqres.in/img/faces/7-image.jpg\"\r\n" + "}";
Expectation[] expectations = new MockServerClient("localhost", mockServer.getLocalPort())
.when(request("/api/users/{userId}")
.withPathParameter(Parameter.param("userId", "1"))
)
.respond(
response()
.withBody(body)
);
System.out.println(expectations);
}
@AfterAll
public static void stopMockServer() {
mockServer.stop();
}
@Test
public void simpleTest() {
Builder aBuilder = new Builder();
aBuilder.path("classpath:test/java/file/callApi.feature");
Results result = aBuilder.parallel(1);
Assertions.assertEquals(0, result.getFailCount());
}
}