How can I mock REST services for automated testing in Groovy? - spring

I'm working on a client code that interfaces with a remote REST service but I'm not exactly sure how to go about mocking the service for my automated tests. I've seen this guide on how to test GORM REST, which I thought I could use as reference, but it looks like it requires a Grails environment to run fine. I'm pretty sure I can incorporate Spring Test into my Groovy project but there are other things I'm not clear about. In particular, I'm not sure how to make the following lines from the link work on plain Groovy project:
RestTemplate rt = Book.restBuilder.restTemplate
final MockRestServiceServer mockServer = MockRestServiceServer.createServer(rt)
In the given guide, Book is a Grails domain class. in the first line above, it refers to a restBuilder property, and I don't know where it came from. The main concern here, I guess, is getting an instance of RestTemplate which I'm not very familiar with.
To be clear, I don't have to stick with this approach. Setting up RestTemplate looks a little complicated without the Grails environment, so if there are other tools that would allow me to mock REST services more easily in a plain Groovy project, I'd be happy to consider them.

Related

What is correct way writing Integration test in Spring or Spring Boot based application

I am writing code for Spring Boot Rest application which interact with DB using Spring JPA.
My app have 3 main layers Controller,Service,Repository and it have CURD operations.
I want to follow TDD approach. My question is how do I populate data for each VERB implementation.
For example I am starting with CREATE impl and implemented CREATE flow with Controller,Service,Repo etc. Now to implement PUT,GET,DELETE I need to populate data while writing my tests. For this purpose I used Injecting Repository in my Integration test class and loaded data before my actual Test Runs or Used DataLoader with CommandLineRunner Implemention to pre-populate the data. Buy my collegue insisted me I should never use Repository in Integration Test class for populating data instead should User Service class bean and call CREATE implementation for required data population.
Is it any best practice or guideline documentation to design Integration Test and Unit Test?
And main question did we use Repository in Integration Test class for populating data or not?
The main motive of writing integration testing is to test the interface between two software units or modules. It focuses on determining the correctness of the interface. That means you should test your application in the sense of whether your app can be integrated into other software or not. In that case, your beans like repositories or services are not injectable or applicable from the other software except your endpoints that you are exposing through controllers.
Writing Integration Test
There are a couple of things you should consider before writing your integration test such as the scope of your test cases, scenarios of each endpoint, tools/libraries to write the tests, etc.
You can use something like RestTemplate or MockMvc to invoke HTTP requests(POST, PUT, CREATE, DELETE). For example, make a GET request with RestTemplate,
#Autowired
private RestTemplate restTemplate;
#Test
void givenYourObjectTypes_whenGetYourObjectTypes_thenStatus200()
ResponseEntity<YourObjectType> response = restTemplate.getForEntity(requestUrl, YourObjectType.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
My question is how do I populate data for each VERB implementation.
There are annotations called BeforeEach and BeforeAll, you can use either of them in a setup method to populate your data
Is it any best practice or guideline documentation to design Integration Test and Unit Test?
There are a lot of documentations you can find out in google. But once you grasp the core concept of the test, you will be intimated to workaround. Still, I would refer to you to have a look at an article by Martin Fowler on Integration Test (It's my personal preference).
And the main question did we use Repository in Integration Test class for populating data or not?
Populating data using repositories is not the recommended approach. Instead, I suggest you use CREATE API to populate data which would be a real scenario while integrating with other services/UI/modules/software.
Moreover, You could try H2 dependency with scope test while testing your application which makes it faster to perform the test cases. But note that it is only applicable if you are using SQL database.

spring rest doc - service layer mocking

recently i saw the blog post say that "for documentation purpose, we use mocking for service layer (in environment using spring rest doc)", so this post use annotation like spring's #MockBean to service layer object.
but i think, if i mock service layer -> spring rest doc always success to test because mocked service object always return intended result and spring rest doc test always receives same intended result from mocked service object.
so i think that is not right but,
i want to know about what is better or how you use service object with spring rest doc
pleas answer
Whether or not it's a good idea to mock the service layer when using Spring REST Docs is largely down to personal preference.
A possible disadvantage of mocking the service layer is that it may be possible for the documentation to get out of sync with the service's actual behaviour. This undermines REST Docs' ability to help you to keep your documentation and service in sync.
An advantage of mocking the service layer is that it can make it easier to document error scenarios or scenarios that would otherwise require quite a lot of setup. In the case of errors, I think you are better adopting a common approach across your whole API and making consistent use of standard HTTP error codes. If you do this, the need to document error responses for each endpoint in a service is reduced.
This leaves documenting more complex scenarios that require a lot of setup. In this case, limited use of mocks may be worthwhile but I would still aim to produce as much of your documentation as possible without relying on mocks.

Start a springboot project for each test case

We are developing test cases for a micro service using Spring Boot. One of the requirement is that for each Junit test case we need to:
start the project
test a unit case and
then stop the project .
I feel this is an anti pattern, but this is the requirement.
I looked around internet but couldn't find a solution for the same. I was able to start a web server but it provided no response and this might be because the project is not assigned to the server.
Does anyone have any idea on how this can be achieved?
PS: We don't want to use Mockito
Before hand i want to make clear that this a very bad practice and should be avoided. This approach does not implement unit tests concept correctly because you are testing an entire system up, so JUnit wouldn't be the correct tool.
I pocked around and i don't seem to find a Runner that may be able to do this (does not surprise me although), the most similar Runner may be SpringJUnit4ClassRunner which provides you a complete Spring context in your test space, but won't go live with the application.
An approach i'd suggest if you really want to go with this is to use tools like REST Assured to do End-to-End API layer tests against the live application, but this implies that you have to find another way to start the app, and then point the REST Assured tests to that started app. Maybe a shell script that starts the app and then starts the REST Assured tests suits, then when the suit ends put down the server.
I highly suggest you to chat with your product/management teams to avoid this kind of stuff since the tests will take FOREVER to run and you will be polluting your local or remote DBs if you are persisting data or other systems through REST or SOAP calls.

Spring REST Docs interrogating #RestController?

I'm looking at Spring REST Docs and wondering if it has the ability to interrogate #RestController methods to produce basic documentation describing a Rest API (methods, http method, parameters, response type)? I believe Springfox Spring/Swagger does that, and would be easier than having to write a test to get that basic info/documentation.
Also, since I don't want to run integration tests in a Production environment, is the Spring RestDocs approach to run your integration tests in a Test environment and then copy the generated docs/snippets into the war so it can be viewed in a Prod environment?
I'm looking at Spring REST Docs and wondering if it has the ability to interrogate #RestController methods to produce basic documentation describing a Rest API
Spring REST Docs is test-driven and deliberately doesn't take the approach of introspecting #RestController methods. You REST API documentation is describing HTTP requests and responses. By being test-driven and working with real or mocked HTTP requests and responses, REST Docs ensures that what you're documenting is what users of your API will be dealing with.
The problem with introspecting #RestController methods is that it's only one small piece of the puzzle. When an HTTP request is received it passes through filters, interceptors, HTTP message conversion etc before it reaches your controller. The same is true in reverse when a response is being sent. Without a complete understanding of everything that happens before your controller's called and everything that happens after your controller returns, the documentation is at risk of being inaccurate.
is the Spring RestDocs approach to run your integration tests in a Test environment and then copy the generated docs/snippets into the war so it can be viewed in a Prod environment
Correct. The documentation is generated once at build time and then typically served as static files from your application. Details of how to do this with Spring Boot are included in the documentation.
This approach has the advantage that none of the code that's involved in creating the documentation is running in production. That reduces your application's footprint, and avoids the possibility of the code that's generating the documentation from causing a problem in production. I believe you can take a similar approach with code-first Swagger tools but, in my experience, it's unusual for people to do so.
Swagger is best choice for me. You cannot do make docs with Spring Rest Docs without integration tests. It's good article reviews rest tools

Good strategy for Spring Framework end-to-end testing

So this is a rather "big" question, but what I'm trying to accomplish is the following:
I have a Spring application, MVC, JDBC (MySQL) and JSP running on tomcat.
My objective is to test the entire "stack" using a proper method.
What I have so far is Junit using Selenium to simulate an actual user interacting with the application (requires a dummy account for that), and performing different validations such as, see if element is present in the page, see if the database has a specific value or if a value matches the database.
1st concern is that this is actually using the database so it's hard to test certain scenarios. I would really like to be able to mock the database. Have it emulate specific account configs, data states etc
2nd concern is that given the fact that I use what is in the database, and data is continuously changing, it is hard to predict behavior, and therefore properly asserting
I looked at Spring Test but it allows for testing outside a servlet container, so no JSP and no Javascript testing possible.
I saw DBUtils documentation but not sure if it will help me in this case
So, to my fellow developers, I would like to ask for tips to:
Run selenium tests on top of a mocked database
Allow different configs per test
Keep compatibility with Maven/Gradle
I have started with an ordered autowire feature to support this kind of stubbing.
It's basically an idea that i took over from the Seam framework i was working with in the past but i couldnt find yet a similar thing in spring.
The idea is to have a precedence annotation (fw, app,mock,...) that will be used to resolve the current implementation of an autowired bean. This is easy already in xml but not with java config.
So we have our normal repository beans in with app precedence and a test package stubbing these classes with mock precedence.
If both are in the classpath spring would normally fail with a duplicate bean found exception. In our case the extended beanfactory simply takes the bean with the highest precedence.
Im not sure if the order annotation of spring could be used directly but i prefered to have "well defined" precedence scopes anyway, so it will be clear for our developers what this is about.
! While this is a nice approach to stub so beans for testing i would not use it to replace a database definition but rather go with an inmemory database like hsql, like some previous answers mentionned already. !

Resources