Exposing endpoint URL in tests - java

Let's go straight to the problem:
I want to test a method that wants URL of Rest endpoint as a parameter. That method is using RestTemplate internally to send a request to that URL, so it needs to be full URL, for example http://localhost:8080/rest. Because of that I also have no way to mock RestTemplate.
I wanted to create simple #RestController but it seems that Spring is not creating endpoint when running tests.
I've tried creating MockMvc but it's not what I want. I have no way of getting the IP and port of MockMvc's created endpoint because no actual endpoint is created.
So, what I want is to make my #RestController accessible in tests by sending requests to URL, for example: http://localhost:8080/rest.
It's my first time creating a test like that, I will be grateful for your help. I was searching for an answer but I couldn't find a solution for my problem.
Edit:
Here's some code:
Unfortunately I can't post all the code but what I'm posting should be enough:
I have my endpoint like(names changed):
#RestController
public class EndpointController {
#RequestMapping(value = "/rest", method = RequestMethod.POST)
public List<Output> doSomething(#RequestBody Input[] requestList){
...
}
}
It's endpoint only for testing, it mimics the real endpoint. Then during my test I'm creating an object like:
new EndpointClient("http://localhost:8080/rest")
which has inside something like this:
ResponseEntity<Output[]> responseEntity = restTemplate.exchange(endpointURL,HttpMethod.POST, httpEntity, Output[].class);
Method having restTemplate request isn't called directly during testing(it's called by another method).
So I need to pass that URL to the Client object.

If you want to test your web application, checkout the Getting Started: Testing the Web Layer documentation.
Spring Boot is providing some useful annotations like #SpringBootTest, #AutoConfigureMockMvc, ...
See also the TestRestTemplate, which can be autowired to your WebMvcTest.
edit:
An example, copied from the documentation mentioned above:
package hello;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
#LocalServerPort
private int port;
#Autowired
private TestRestTemplate restTemplate;
#Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
String.class)).contains("Hello World");
}
}

I found a solution for my problem.
I did it with WireMock: http://wiremock.org/
First I had to create Transformer for my request, so the response depends on request, something like:
public class MyTransformer extends ResponseTransformer {
#Override
public Response transform(final Request request,
final Response response,
final FileSource fileSource,
final Parameters parameters){
HttpHeaders headers = new HttpHeaders(new HttpHeader("Content-Type", "application/json"));
if(request.getUrl().contains("/rest")){
...
return Response.Builder.like(response).but().body(...).headers(headers).build();
} else
return Response.Builder.like(response).but().status(404).headers(headers).build();
}
#Override
public String getName() {
return "swapper";
}
}
In my test I needed to put
WireMockServer server = new WireMockServer(wireMockConfig().port(3665).extensions("package.name.endpoint.MyTransformer"));
server.stubFor(post("/rest"));
It created exactly what I wanted. Code above is extremely simple, probably not that good and needs work but it shows the basics.

Related

Custom AOP spring boot annotation with ribbon client blocking api call with return "1"

I have really poor experience with ribbon/eureka so forgive me if this is a stupid question:
I have two different microservice both connected to a discovery server, the first one calls the second using a custom annotation that sends a request using rest template.
Custom annotation name is PreHasAuthority
Controller :
#PreHasAuthority(value="[0].getProject()+'.requirements.update'")
#PostMapping(CREATE_UPDATE_REQUIREMENT)
public ResponseEntity<?> createUpdateRequirement(#Valid #RequestBody RequirementDTO requirementDTO
, HttpServletRequest request, HttpServletResponse response) {
return requirementService.createUpdateRequirement(requirementDTO, request, response);
}
Annotation interface :
import java.lang.annotation.*;
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface PreHasAuthority {
String value();
}
Annotation implementation:
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import netcomgroup.eu.service.AuthenticationService;
#Aspect
#Component
public class PreHasAuthorityServiceAspect {
#Autowired
private AuthenticationService authenticationService;
#Around(value = "#annotation(PreHasAuthority)")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
PreHasAuthority preHasAuthority = method.getAnnotation(PreHasAuthority.class);
Object[] args = joinPoint.getArgs();
String permission = preHasAuthority.value();
ExpressionParser elParser = new SpelExpressionParser();
Expression expression = elParser.parseExpression(permission);
String per = (String) expression.getValue(args);
String token =null;
for(Object o : args) {
if(o instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest)o;
token=request.getHeader("X-Auth");
break;
}
}
if(token==null) {
throw new IllegalArgumentException("Token not found");
}
boolean hasPerm = authenticationService.checkPermission(per,token);
if(!hasPerm)
throw new Exception("Not Authorized");
}
}
My Ribbon configuration
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
public class RibbonConfiguration {
#Autowired
IClientConfig config;
#Bean
public IRule ribbonRule(IClientConfig config) {
return new RoundRobinRule();
}
}
Eureka config in application properties
#Eureka config
eureka.client.serviceUrl.defaultZone= http://${registry.host:localhost}:${registry.port:8761}/eureka/
eureka.client.healthcheck.enabled= true
eureka.instance.leaseRenewalIntervalInSeconds= 10
eureka.instance.leaseExpirationDurationInSeconds= 10
by calling the api from postman request is sendend correctly to the second microservice and i'm certain the return is "true".
After that the request stops before entering the createUpdateRequirement method and returns '1' as postman body response. No error of sort is provided.
My guess is that the problem resides within the custom annotation, cause when i remove the annotation the api call works perfectly, but i cannot understand the problem as it seems all setted up correctly to me.
Your #Around advice never calls joinPoint.proceed(). Hence, the intercepted target method will never be executed.
The second problem is that your advice method returns void, i.e. it will never match any method returning another type such as the ResponseEntity<?> createUpdateRequirement(..) method.
Besides, around is a reserved keyword in native AspectJ syntax. Even though it might work in annotation-driven syntax, you ought to rename your advice method to something else like aroundAdvice or interceptPreHasAuthority - whatever.
Please do read an AspectJ or Spring AOP tutorial, especially the Spring manual's AOP chapter. 😉

Testing camel routes

I have multiple routes classes defined in my project under com.comp.myapp.routes.
For testing these I am mocking the end route and checking/comparing delivery received.
Say for example I have below routes:
public class MyRoute1 extends RouteBuilder {
public void configure() throws Exception {
//Route_1 code
}
}
public class MyRoute2 extends RouteBuilder {
public void configure() throws Exception {
//Route_2 code
}
}
....
...//some route impl
..
public class MyRouteN extends RouteBuilder {
public void configure() throws Exception {
//Route_N code
}
}
Now for all these routes the test case that I wrote seems same.
First mock it.
Mock for MyRoute1:
public class MyRoute1_Mock extends RouteBuilder {
public void configure() throws Exception {
from("direct:sampleInput")
.log("Received Message is ${body} and Headers are ${headers}")
.to("mock:output");
}
}
Test for MyRoute1:
public class MyRoute1_Test extends CamelTestSupport {
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new MyRoute1_Mock();
}
#Test
public void sampleMockTest() throws InterruptedException {
String expected="Hello";
/**
* Producer Template.
*/
MockEndpoint mock = getMockEndpoint("mock:output");
mock.expectedBodiesReceived(expected);
String input="Hello";
template.sendBody("direct:sampleInput",input );
assertMockEndpointsSatisfied();
}
}
Now to make unit test for other classes just copy and paste the above code with different name say MyRoute2_Test , MyRoute3_Test , ...MyRouteN_Test.
So what did it actually tested?
It's just written for the purpose of writing test case.
It actually just checks/tests if mock library and camel-test library work or not Not our code works or not?
How should it actually be done?
You want to test your Camel routes but in the test you mock them away. So yes, you are testing your route mock instead of the real route.
To test your real routes:
Send a message to your real routes from endpoint
If this is not easy, mock your from endpoint (not the entire route!) by replacing it with a direct endpoint. This is quite easy with adviceWith
The test message is going through your route
Assert that any to endpoint receives the correct message by mocking these endpoints too. Again, use adviceWith for that. And Camel Mock of course
You can get the received messages (Exchanges) from a Camel Mock to do in depth assertions
If you got the happy test, start to write negative tests by injecting errors in your route. adviceWith can help here too
... and so on
If you are completely new to Camel route tests, get Camel in Action 2nd edition. It explains all mentioned testing aspects for Camel applications on 65 pages. And of course it also takes you on a complete ride through the Camel universe on much more pages.
By the way: if testing your routes is hard, they are too complex. Start to divide your routes so that they are easily testable.
The route you show doesn't really do anything to the messages traversing it, so testing that the same text you sent in one end comes out the other is all there is to test.
For routes with more data transformation and processing, you could test the output data types, that processors were called when needed, you could mock in throwing of exceptions, etc. What you have above is a good start on that.
Explained in-line,Hope this helps you understand significance of Mock in Unit Test:
public void sampleMockTest() throws InterruptedException {
String expected="Hello";
MockEndpoint mock = getMockEndpoint("mock:output");//Mocking endpoint
mock.expectedBodiesReceived(expected); //Setting expected output to mocked endpoint
String input="Hello";
template.sendBody("direct:sampleInput",input );//triggering route execution by sending input to route
assertMockEndpointsSatisfied(); //Verifies if input is equal to output
}
If your endpoint is Rest service you can make use of "TestRestTemplate" instead of Mocking it and Test like below:
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleCamelApplicationTest {
}
import org.springframework.boot.test.web.client.TestRestTemplate;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleCamelApplicationTest {
#Autowired
private TestRestTemplate restTemplate;
}
#Test
public void sayHelloTest() {
// Call the REST API
ResponseEntity<String> response = restTemplate.getForEntity("/camel/hello", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
String s = response.getBody();
assertThat(s.equals("Hello World"));
}

Best way to unit test JAX-RS Controller?

I am learning the library javax.ws.rs so I wrote a toy API.
For instance, I've got this POST method working. I've seen that there are many libraries for testing, like Jersey or Rest Assured, but, how can I unit test that response code is 200 and that the content is "hello"?
#POST
#Path("/getFoo")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
Foo getFoo(#BeanParam final Foo foo)
{
return new Foo("hello");
}
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a comparison/setup of both (http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/).
package com.example.rest;
import static com.jayway.restassured.RestAssured.expect;
import groovyx.net.http.ContentType;
import org.junit.Before;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
public class Products{
#Before
public void setUp(){
RestAssured.basePath = "http://localhost:8080";
}
#Test
public void testGetProducts(){
expect().statusCode(200).contentType(ContentType.JSON).when()
.get("/getProducts/companyid/companyname/12345088723");
}
}

Using #RequestLine with Feign

I have a working Feign interface defined as:
#FeignClient("content-link-service")
public interface ContentLinkServiceClient {
#RequestMapping(method = RequestMethod.GET, value = "/{trackid}/links")
List<Link> getLinksForTrack(#PathVariable("trackid") Long trackId);
}
If I change this to use #RequestLine
#FeignClient("content-link-service")
public interface ContentLinkServiceClient {
#RequestLine("GET /{trackid}/links")
List<Link> getLinksForTrack(#Param("trackid") Long trackId);
}
I get the exception
Caused by: java.lang.IllegalStateException: Method getLinksForTrack not annotated with HTTP method type (ex. GET, POST)
Any ideas why?
I wouldn't expect this to work.
#RequestLine is a core Feign annotation, but you are using the Spring Cloud #FeignClient which uses Spring MVC annotations.
Spring has created their own Feign Contract to allow you to use Spring's #RequestMapping annotations instead of Feigns. You can disable this behavior by including a bean of type feign.Contract.Default in your application context.
If you're using spring-boot (or anything using Java config), including this in an #Configuration class should re-enable Feign's annotations:
#Bean
public Contract useFeignAnnotations() {
return new Contract.Default();
}
The reason I got this error is that I used both #FeignClient and #RequestLine annotations in my FooClient interface.
Before a fix.
import org.springframework.cloud.openfeign.FeignClient; // #FeignClient
import feign.RequestLine; // #RequestLine
import org.springframework.web.bind.annotation.PathVariable;
#FeignClient("foo")
public interface FooClient {
#RequestLine("GET /api/v1/foos/{fooId}")
#Headers("Content-Type: application/json")
ResponseEntity getFooById(#PathVariable("fooId") Long fooId); // I mistakenly used #PathVariable annotation here, but this should be #Param
}
Then, I got this error.
Caused by: java.lang.IllegalStateException: Method FooClient#getFooById(Long) not annotated with HTTP method type (ex. GET, POST)
After a fix
// removed #FeignClient
// removed #PathVariable
import feign.Param; // Added
import feign.RequestLine; // #RequestLine
// removed #FeignClient("foo")
public interface FooClient {
#RequestLine("GET /api/v1/foos/{fooId}")
#Headers("Content-Type: application/json")
Foo getFooById(#Param("fooId") Long fooId); // used #Param
}
If you are interested in the configuration classes.
Please note that I tried to create Feign Clients Manually.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScans(value = {
#ComponentScan(basePackages = {
"com.example.app.service.web.client",
})
})
public class FeignConfig {
#Value(value = "${app.foo.service.client.url}")
protected String url; // http://localhost:8081/app
#Bean
public FooClient fooClient() {
FooClient fooClient = Feign.builder()
// .client(RibbonClient.create())
.client(new OkHttpClient())
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger(FooClient.class))
.logLevel(Logger.Level.FULL)
.target(FooClient.class, url);
return fooClient;
}
}
References
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html
https://www.baeldung.com/intro-to-feign
https://www.baeldung.com/feign-requestline
https://stackoverflow.com/a/32488372/12898581
Your #RequestMapping value looks ok, but you're likely should consider slightly rewriting it:
#GetMapping(value = "/{trackid}/links")
List<Link> getLinksForTrack(#PathVariable(name = "trackid") Long trackId);
Btw I did not succeeded with getting #RequestLine to work due to same error as yours.
Also for #ReactiveFeignClients Contract.Default() yields to following errors:
java.lang.IllegalStateException: Method MyClient#doStuff(String,String) not annotated with HTTP method type (ex. GET, POST)
Warnings:
- Class MyClient has annotations [Component, ReactiveFeignClient, Metadata] that are not used by contract Default
- Method doStuff has an annotation GetMapping that is not used by contract Default
and should be fixed like:
var MyClient = WebReactiveFeign.builder()
.contract(new ReactiveContract(new SpringMvcContract()))
.target(MyClient, "http://example.com")

Unit testing jersey Restful Services

I'm new to unit testing and I want to test some jersey services in a project. We are using Junit. Please guide me to write test cases in better way.
CODE:
#GET
#Path("/getProducts/{companyID}/{companyName}/{date}")
#Produces(MediaType.APPLICATION_JSON)
public Object getProducts(#PathParam("companyID") final int companyID,
#PathParam("date") final String date, #PathParam("companyName") final String companyName)
throws IOException {
return productService.getProducts(companyID, companyName, date);
}
Above mentioned service is working fine and I want to write junit test case to test above mentioned method. Above method will retrieve list of products (List<Product>) in JSON format. I would like to write test case to check response status and json format.
NOTE: We are using Jersey 1.17.1 version.
Help would be appreciated :)
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (already mentioned in other answer - see here documentation for version 1.17 here: https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a comparison/setup of both (http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/).
I find the REST-Assured more interesting and powerful, but Jersey Test Framework is very easy to use too. In REST-Assured to write a test case "to check response status and json format" you could write the following test (very much like you do in jUnit):
package com.example.rest;
import static com.jayway.restassured.RestAssured.expect;
import groovyx.net.http.ContentType;
import org.junit.Before;
import org.junit.Test;
import com.jayway.restassured.RestAssured;
public class Products{
#Before
public void setUp(){
RestAssured.basePath = "http://localhost:8080";
}
#Test
public void testGetProducts(){
expect().statusCode(200).contentType(ContentType.JSON).when()
.get("/getProducts/companyid/companyname/12345088723");
}
}
This should do the trick for you... you can verify JSON specific elements also very easily and many other details. For instructions on more features you can check the very good guide from REST-Assured (https://code.google.com/p/rest-assured/wiki/Usage). Another good tutorial is this one http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework/.
HTH.
Just ignore the annotations and write a normal unit test that passes the required parameters. The return I thought would usually be of type "javax.ws.rs.core.Response" ... There is a getEntity() method on that can be used. Using a Mock object framework like Mockito could be helpful in this case too.
Are you familiar with Chapter 26. Jersey Test Framework?
public class SimpleTest extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void test() {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}

Categories

Resources