RestAssured: Can't find the equalTo method - java

I am using the following code for making the service call using the Rest assured library, can you help me to resolve the build issues. There is a problem in finding the function "equalTo" to validate the response data.
See error below:
Here is my code:
#Test
public void testFileUpload() {
final File file = new File(getClass().getClassLoader()
.getResource("test.txt").getFile());
assertNotNull(file);
assertTrue(file.canRead());
given()
.multiPart(file)
.expect()
// problem here
.body(equalsTo("This is an uploaded test file."))
.when()
.post("/service/file/upload");
}
#Test
public void testGetSingleUser() {
given()
.expect()
.statusCode(200)
.body(
"email", equalTo("test#hascode.com"),
"firstName", equalTo("Tim"),
"lastName", equalTo("Testerman"),
"id", equalTo("1"))
.when()
.`enter code here`
.get("/service/single-user");
}

I assume it is the equalTo from the hamcrest library.
Can you add this import and see if it works
import static org.hamcrest.Matchers.equalTo;

import static org.hamcrest.Matchers.equalTo;
With adding above hamcrest library, Error will be resolved.
I have tried and it worked.

Import this Line you will get the equalTo()
import static org.hamcrest.Matchers.*;

Related

Cannot validate email values in restapi using restassured

can someone please assist, I'm using restassured to pull and display results from this server https://jsonplaceholder.typicode.com/posts/9/comments, but cannot verify the emails of this user and display accurate data. Here is my code below:
public static void getPostComments() {
System.out.println("===============Comments By User==================");
given().when().get(url + "/posts/9/comments").then().log()
.body();
Response res = given().when().get(url + "/posts/9/comments");
List<String> jsonRes = res.jsonPath().getList("email");
if (jsonRes.equals("Lucio#gladys.tv")) {
given().queryParam("id", "9")
.get("http://localhost:3000/posts/9/comments/")
.then()
.assertThat()
.body("email["+String.valueOf(0)+"]", Is.is("Lucio#gladys.tv"))
.log()
.body();
}
}
The results I get from the above code, just returns all the users without validating. I'm fairly new to restassured, but would appreciate any pointers to validate these emails.
There are many ways to do that.
Example 1:
given()
.get("https://jsonplaceholder.typicode.com/posts/9/comments")
.then()
.assertThat()
.body("email", hasItem("Lucio#gladys.tv"));
Example 2:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
List<String> emails = given()
.get("https://jsonplaceholder.typicode.com/posts/9/comments")
.jsonPath()
.get("email");
assertThat(emails, hasItem("Lucio#gladys.tv"));

WireMock: Stubbing - Not able to implement "AssertThat" method correctly

I'm struggling to create a simple stub. I've been following the wiremock tutorial online but have had no success on the issue im facing. Particularly, the "Get" method in the AssertMethod is giving me a lot of issues. I don't know how to resolve it.
public class WeatherApplicationTest {
#Rule
public WireMockRule wireMockRule = new WireMockRule();
public WireMockServer wireMockServer = new WireMockServer(); //No-args constructor will start on port 8080, no HTTPS
#BeforeClass
public void setUpClass() {
wireMockServer.start();
}
#AfterClass
public void tearDownClass() {
wireMockServer.stop();
}
#Test
public void statusMessage() throws IOException{
wireMockRule.stubFor(get(urlEqualTo("/some/thing"))
.willReturn(aResponse()
.withStatus(200)
.withStatusMessage("Everything is fine")
.withHeader("Content-Type", "Text/Plain")));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:" + wireMockServer.port() + "/some/thing");
HttpResponse response = client.execute(request);
assertThat(response.GET("/some/thing").statusCode(), is(200));
}
}
I'm getting an error on the following line:
assertThat(response.GET("/some/thing").statusCode(), is(200));
The GET method is underlined in Red.
Please Help!
The WireMock documentation doesn't do a great job of outlining how to connect with it (but, in their defense, it's not really in their slice of the pie).
As I eluded to in the comments, HttpResponse does not contain a GET() method, which is why you're getting the "red underline" (IE: error).
So we know we are looking to make an assertion against the status code. If we look at the Javadoc of the HttpResponse class, there is the StatusLine class that can be retrieved from getStatusLine() of HttpResponse, and the Javadoc of that class shows that it contains a getStatusCode() method. Combining this information into your answer, the assertion needs to be updated to:
assertThat(response.getStatusLine().getStatusCode(), is(200));
In addition, as pointed out by Tom in the comments, remove the WireMockServer (as well as the start/stop and getPort() calls; you can get the port from your rule. And the stubFor(...) method should be called statically (not as a part of the rule).
My contribution to this question: this Java test runs without exceptions, both in the IDE and in Maven as well, and, moreover with the other tests, because at the end, it shuts down the mock server, and doesn't make any conflicts with other servers running in the other tests.
import com.github.tomakehurst.wiremock.WireMockServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import wiremock.org.apache.http.HttpResponse;
import wiremock.org.apache.http.client.HttpClient;
import wiremock.org.apache.http.client.methods.HttpGet;
import wiremock.org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class KatharsisControllerTest {
private static WireMockServer mockedServer;
private static HttpClient client;
#BeforeClass
public static void setUpClass() {
mockedServer = new WireMockServer();
mockedServer.start();
client = new DefaultHttpClient();
}
#AfterClass
public static void tearDown() {
mockedServer.stop();
}
#Test
public void test_get_all_mock() {
stubFor(get(urlEqualTo("/api/Payment"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/vnd.api+json;charset=UTF-8")
.withStatus(200)
.withBody("")
));
HttpGet request = new HttpGet("http://localhost:8080/api/Payment");
try {
HttpResponse response = client.execute(request);
assert response.getStatusLine().getStatusCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
}
}

Shiro: How to write a test for an endpoint protected with #RequiresRoles?

Say I have this resource:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
#Path("/authhello")
#Api(value = "hello", description = "Simple endpoints for testing api authentification",
hidden = true)
#Produces(MediaType.APPLICATION_JSON)
#RequiresAuthentication
public class AuthenticatedHelloWorldResource {
private static final String READ = "READ";
private static final String WRITE = "WRITE";
#GET
#ApiOperation(value = "helloworld",
notes = "Simple hello world.",
response = String.class)
#RequiresRoles(READ)
public Response helloWorld() {
String hello = "Hello world!";
return Response.status(Response.Status.OK).entity(hello).build();
}
#GET
#Path("/{param}")
#ApiOperation(value = "helloReply",
notes = "Returns Hello you! and {param}",
response = String.class)
#RequiresRoles(WRITE)
public Response getMsg(#PathParam("param") String msg) {
String output = "Hello you! " + msg;
return Response.status(Response.Status.OK).entity(output).build();
}
}
Should I write tests that confirm that certain (test) users get a response from the endpoints, and certain users don't? And if so: How can I write those tests? I've tried something like this:
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import com.cognite.api.shiro.AbstractShiroTest;
import static org.junit.Assert.assertEquals;
public class AuthenticatedHelloWorldTest extends AbstractShiroTest {
#Override
protected Application configure() {
return new ResourceConfig(AuthenticatedHelloWorldResource.class);
}
#Test
public void testAuthenticatedReadHelloWorld() {
final String hello = target("/authhello").request().get(String.class);
assertEquals("Hello world!", hello);
}
#Test
public void testAuthenticatedWriteHelloWorld() {
final String hello = target("/authhello/test").request().get(String.class);
assertEquals("Hello you! test", hello);
}
}
but I'm not sure how to actually test the function of the #RequiresRoles-annotation. I've read Shiro's page on testing, but I haven't been able to write a failing test (e.g. a test for a subject that does not have the WRITE role trying to access /authhello/test). Any tips would be appreciated.
Should I even test this?
Yes. Provided you want to make sure that certain roles will have or have not access to your resource. This will be a security integration test.
How should I go about setting up the whole application + actually call it with an http request in a test if I am to test it? Or is there a simpler way?
Part of the issue is that #RequiresAuthentication and #RequiresRoles themselves are just class and method meta information. Annotations themselves do not provide the security check functionality.
It is not clear from your question what type of container you are using but I can guess that it is plain Jersey JAX-RS service (am I right?). For Shiro to perform security checks you should have added some JAX-RS filter (maybe some other way?) around your endpoints. To test security you should replicate this setup in your tests. Otherwise there is no engine processing your annotations and no security checks as the result.

Cannot print api response on console

For some reason, when I try to print the response using print statement for the response body, the system does not print. please help.
In the following API post, I am using Java, rest-assured, TestNG on Eclipse Neon 3. Using #DataProvider annotation, I am passing multiple params in Post request to see the response of the call. Any help would be truly appreciated.
package com.auto.restassured;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.basic;
import static io.restassured.RestAssured.given;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.restassured.response.Response;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
public class FilePostToVirusTotal {
static String baseURL = "https://www.virustotal.com/vtapi/v2/file/report";
Response myResponse;
#DataProvider(name = "md5hashes")
public String[][] createMd5Hashes() {
return new String[][] {
{"md51", "c1105fb75bc00b5e487f7b26a5be7088"},
{"md52", "213f3287c81d09b095334c9f3151cff8"},
{"md53", "b00c2c458b4cf1eb172e354f54f0fe12"},
{"md54", "32ac9b6b6b7cdbfce179acc5edae98c3"},
{"md55", "510b0b81b85c025d538ed4bad78dc64f"},
};
}
#Test(dataProvider = "md5hashes")
public void md5JsonTest(String apikey, String resource)
{
//Catch API response
myResponse = given().param("text", resource).param("text", "34b937e6e2d28ee6f93a70392d958de8ac4a8dd842e08bbca9bcb0d22f9b9960").when().post(baseURL);
//Print Response
System.out.println(myResponse.getBody().asString());
}
}
You can use built-in log methods e.g. given().log().all() for request and then().log().all() for response
public class Request {
public static void main(String[] args) {
RestAssured.baseURI="http://dummy.restapiexample.com";
given().
//queryParam("key","AIzaSyDIQgAh0B4p0SdyYkyW8tlG-y0yJMfss5Y").
body("{\"name\":\"test111\",\"salary\":\"123\",\"age\":\"23\"}").
when().
post("/api/v1/create").
then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and()
.body("status",equalTo("success")).log().body();
System.out.println("Done");
}
}
Result:
{
"status": "success",
"data": {
"name": "test111",
"salary": "123",
"age": "23",
"id": 65
}
}
Done

How to check JSON in response body with mockMvc

This is my method inside my controller which is annotated by #Controller
#RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
#ResponseBody
public JSONObject getServerAlertFilters(#PathVariable String serverName) {
JSONObject json = new JSONObject();
List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
JSONArray jsonArray = new JSONArray();
jsonArray.addAll(filteredAlerts);
json.put(SelfServiceConstants.DATA, jsonArray);
return json;
}
I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as my json.
And this is my JUnit test:
#Test
public final void testAlertFilterView() {
try {
MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
.accept("application/json"))
.andDo(print()).andReturn();
String content = result.getResponse().getContentAsString();
LOG.info(content);
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the console output:
MockHttpServletResponse:
Status = 406
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Even result.getResponse().getContentAsString() is an empty string.
Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.
I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below
#Test
public void testAlertFilterView() throws Exception {
this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").
.andExpect(status().isOk())
.andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}"));
}
If you want check check json Key and value you can use jsonpath
.andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));
You might find thatcontent().json() are not solveble please add
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
The 406 Not Acceptable status code means that Spring couldn't convert the object to json. You can either make your controller method return a String and do return json.toString(); or configure your own HandlerMethodReturnValueHandler. Check this similar question Returning JsonObject using #ResponseBody in SpringMVC
You can try the below for get and post methods
#Autowired
private MuffinRepository muffinRepository;
#Test
public void testGetMethod throws Exception(){
Muffin muffin = new Muffin("Butterscotch");
muffin.setId(1L);
BddMockito.given(muffinRepository.findOne(1L)).
willReturn(muffin);
mockMvc.perform(MockMvcRequestBuilders.
get("/muffins/1")).
andExpect(MockMvcResutMatchers.status().isOk()).
andExpect(MockMvcResutMatchers.content().string("{\"id\":1, "flavor":"Butterscotch"}"));
}
//Test to do post operation
#Test
public void testPostMethod throws Exception(){
Muffin muffin = new Muffin("Butterscotch");
muffin.setId(1L);
BddMockito.given(muffinRepository.findOne(1L)).
willReturn(muffin);
mockMvc.perform(MockMvcRequestBuilders.
post("/muffins")
.content(convertObjectToJsonString(muffin))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResutMatchers.status().isCreated())
.andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(muffin)));
}
If the response is empty then make sure to override equals() and hashCode() methods on the Entity your repository is working with:
//Converts Object to Json String
private String convertObjectToJsonString(Muffin muffin) throws JsonProcessingException{
ObjectWriter writer = new ObjectWriter().writer().withDefaultPrettyPrinter();
return writer.writeValueAsString(muffin);
}
There are 2 ways to check JSON responses. Lemme guide you through both of them, (taking test method from the question above, and assuming response {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as given above)
Method 1) Asserting complete JSON
#Test
public final void testAlertFilterView() {
mockMvc.perform(get("/getServerAlertFilters/v2v2v2/")
.contentType("application/json"))
.andExpect(status().isOk())
// you may even read bigger json responses from file and convert it to string, instead of simply hardcoding it in test class
.andExpect(content().json("{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}"))
}
Method 2) Asserting specific key-value of response (not writing redundant piece of code)
.andExpect(jsonPath("$.data[0].useRegEx").value(false))
.andExpect(jsonPath("$.data[0].hosts").value("v2v2v2"));
Another thing you might need is the import statement,
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
If you want to check a few values in a specific field of JSON
.andExpect(MockMvcResultMatchers.jsonPath("$.message",
AllOf.allOf(
StringContains.containsString("name: must not be null"),
StringContains.containsString("type: must not be null")
)));
How it looks in the test class. JUnit4.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.core.AllOf;
import org.hamcrest.core.StringContains;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#RunWith(MockitoJUnitRunner.class)
public class YourControllerTest {
#Mock
private YourService service;
private MockMvc mvc;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders
.standaloneSetup(new YourController(service))
.setControllerAdvice(new YourExceptionHandler())
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
}
#Test
public void yourControllerMethodName_400_validation() throws Exception {
String path = "/orders/{orderId}/items";
Integer orderId = 123;
YourRequestDto requestDto = YourTestFactory.buildYourRequestDto();
requestDto.setName(null);
requestDto.setType(null);
YourResponseDto expected = YourTestFactory.buildYourResponseDto(requestDto);
Mockito
.when(service.someMethod(orderId, requestDto))
.thenReturn(expected);
mvc
.perform(
MockMvcRequestBuilders.post(path, orderId)
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(requestDto))
)
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.message",
AllOf.allOf(
StringContains.containsString("name: must not be null"),
StringContains.containsString("type: must not be null")
)));
}
}

Categories

Resources