How to Mock a Declarative Client in Micronaut? - client

I have Class in which I call a method from a declarative client. But for my test I don't want it to call the actual URL. Instead I want to Mock it. How can I do that as it is not a class but an Interface annotated with #Client?
Example code:- here. Please check section 4.3

In your test you can replace the http client bean with a mock. Please find a Spock snippet below.
// replace the client with a mock
#MockBean(YourClientInterface)
YourClientInterface yourClientInterface() {
return Mock(YourClientInterface)
}
// inject the mock in order to configure responses when it gets called
#Inject
YourClientInterface client
Now you can write tests and your code will run against the mock instead of the actual http client.

Related

Launch spring boot mvc test from custom testng framework

Where I'm working one of our customer required to use a custom test framework written using testng that allows to handle different parameters and test iterations using excel files.
This framework uses a main class to handle all the tests, lets call it TestManager.
This TestManager defines all the #Before and #After operations and has a method called exec() which is annotated as #Test.
This method is used to call the different components required from the test, these components are java classes that implements a single method exec() containing the logic of the single component.
public class TestManager {
// ... Before, After methods
#Test(
dataProvider = "..."
)
public void exec(Parameter[] inParameter) {
// load parameters...
foreach component:
component.exec()
}
}
public class ComponentXYZ {
public void exec() {
// load input params
// Call a microservice and get results, find value on db, selenium operations...
// unload output params for next components
}
}
This framework was designed to be used with selenium, or to test microservices using some http request library and is contained in a standalone module.
So my project has:
A spring boot module
A test module which (in my idea) should have a dependency over the spring boot module
Given this situation do you think it could be possible to use WebMvcTest to perform integration tests while using this custom framework?
I've been trying for a while but I'm always getting errors or I'm not able to #Autowire MockMvc, I can't seem to start a minimal spring boot instance directly from this test framework...
I don't think running my spring boot app and calling the microservices using http is the correct way to test but at this moment is the only thing it's working.

How to unit test a class that makes an external WebClient request?

I have an #Service class that does some null checks and then makes a call to an external micro-service using WebClient. Sonar is complaining that this class is not test because the method is not fully tested. Question is, how can I mock this call or use a mockserver for this? I've tried WebTestClient but I can't seem to get things to work..
public Mono<CartResponse> someServiceCall(BarRequest barRequest)
//some null checks and random logic.
return WebClient.create("http://" + fooHostName)
.post()
.uri(uri)
.body(Mono.just(barRequest), BarRequest.class)
.exchange()
.flatMap(serviceResponse -> {
if (serviceResponse.statusCode().is5xxServerError()) {
//some error logic
return Mono.just(barResponse);
}
return serviceResponse.bodyToMono(BarResponse.class);
});
So I don't want to actually make this call I just want it covered in the test, so I'd like some insight on how to get this either mocked or spin up a mock server.. I've been at this for about a day now..
this is as of yet no supported for mocking WebClient like RestTemplate.
there is an open issue for it on github.
Support of MockRestServiceServer for WebClient
Spring themselves use MockWebServer to test their own code so it's safe to say that it is a viable solution.

Testing ControllerAdvice with AutoConfigureMockMvc and CompletableFuture

I have added a REST controller returning CompletableFutures to a project using a ControllerAdvice to translate exceptions into error DTOs.
My controller doesn’t throw the exceptions, wrapping them into failed CompletableFutures and returning these.
When running the full application and manually testing it works as expected, but in my tests the mockMvc won’t trigger the advices and always return HTTP 2xx.
Any idea why?
If you have a standalone setup of MockMvc, then you need to specify the controller advice to be used (if any) while creating the mockMvc instance as follows:
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new YourControllerAdvice())
.build();
The reason for this is that you don't have a context here for spring to detect the controller advice.
I figured out my test was not correct (or, to put it another way.. the testing framework is not designed as I expected ;)
When testing controllers returning CompletableFutures one needs to use asyncDyspatch as in
https://github.com/spring-projects/spring-framework/blob/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java

How to mock REST service response in actual code flow for lower environments

I have a service which calls the REST Api and that REST API call is chargeable, so i want when we deploy the code in Dev & QA environment, mock response should be returned while actual functionality testing.
How can i achieve that ?
Mock Rest API response in actual code flow
The endpoint for your api shouldn't be hard-coded in the code, instead you can set the endpoint in a properties file.
ie. In a file like .../myapp/src/resources/application.properties
some.service.api.endpoint=someservice.com/api
Then in your code you can use Spring's #Value annotation to get the value.
#Service
public class SomeServiceApi {
#Value("some.service.api.endpoint")
private String endpoint;
// ...
While in development, the property can point to some mock endpoint that you've set up yourself, or if the api supports it, a sandbox endpoint for the api.

Best way to mock complex soap responses

I have a Java method I want to Unit test, but it requires a mocked SOAP response which contains multiple lists and layers of nodes. I am doing this with a handwritten mock i.e. just manually creating the objects and setting the values, but as the response is quite complex its a pain building up the response. I have a sample XML response is there an easy way of creating the mock using the XML?
Also I looked at Mockito and it looks fine for simple Objects, but it doesnt seem that good for complex responses (I may not be using it to its full potential).
The app stack is Java 1.6, Spring 3 and using JAX-WS.
I do something like this
#WebService
public class MyWebService {
#Autowired
private ServiceBean serviceBean;
public SomeReturedData getData(SomeInputData inputData) {
return serviceBean.getData(inputData);
}
}
For my UnitTest, I have a mock instanciation of "ServiceBean" which I inject in to #MyWebService, and "MyWebService" is deployed using the "in-vm" transport as described here
By Using the in-vm transport, All the XML marshalling/unmarshalling is still done by the web-service framework ,and you only have to deal with Java part.
Now someone might ask, why not test the "ServiceBean" directly, why the need to deply a WS using in-vm transport ? Well 2 things, Using in-vm transport you get to test that the JAXB XML marshalling/unmarshalling is working correctly, and it also allows you to test any intercepting handlers that you might have defined for your webservice.

Resources