spring-integration: mock requestFactory on HttpRequestExecutingMessageHandler - mockito

Since upgrading spring-integration to 5.3.10.RELEASE we can't mock the requestFactory on HttpRequestExecutingMessageHandler anymore in the unit tests, it is actually checked if the requestFactory setter has been called and an exception is thrown in that case.
So, how to configure the HttpRequestExecutingMessageHandler.requestFactory now with a Mockito instance?

The check there is like this:
public void setRequestFactory(ClientHttpRequestFactory requestFactory) {
assertLocalRestTemplate("requestFactory");
this.restTemplate.setRequestFactory(requestFactory);
}
That means that you have been providing a RestTemplate into this HttpRequestExecutingMessageHandler. The requestFactory is essentially a property of the RestTemplate. So, consider to set your mock into that external RestTemplate instead.

Related

Micronaut and PowerMock

I am trying to use PowerMock(as i have some legacy static methods) in a micronaut based application. But when I try to run the application all micronaut beans are getting injected as null (and the underlying mocks as well)
#RunWith(PowerMockRunner.class)
#PrepareForTest({MyStaticClass.class, ClassToBeTested.class})
public class TestClass {
#InjectMocks
private ClassToBeTested obj1;
#Mock
private LegacyStaticClass1 obj2;
#Mock
private MicronautBasedBean obj2;
#Before
public void setup(){
MockitoAnnotations.initMocks(this);
MockitoAnnotations.initMocks(this);
}
Is there a #PowerMockRunnerDelegate or PorwerMock runner from micronaut (like SpringRunner)
also my #Before doesntt get called to inject mocks in this case
I tried using
#MicronautTest on the TestClass but then PowerMock is not able to mock static class.
Is there a #PowerMockRunnerDelegate or PorwerMock runner from
micronaut?
Not currently, no. Feel free to file a feature request at https://github.com/micronaut-projects/micronaut-test/issues. We welcome pull requests too of course.

Representing thread pooling in Spring Integration rather than ExecutorService

Currently, code similar to the following exists in one of our applications:
#Component
public class ProcessRequestImpl {
private ExecutorService executorService;
public processRequest(...) {
// code to pre-process request
executorService.execute(new Runnable() {
public void run() {
ProcessRequestImpl.this.doWork(...);
}
}
}
private void doWork(...) {
// register in external file that request is being processed
// call external service to handle request
}
}
The intent of this is to create a queue of requests to the external service. The external service may take some time to process each incoming request. After it handles each one, it will update the external file to register that the specific request has been processed.
ProcessRequestImpl itself is stateless, in that all state is set in the constructor and there is no external access to that state. The process() method is called by another component in the application.
If this were to be implemented in a Spring Integration application, which of the following two approaches would be best recommended:
Keep the above code as is.
Extract doWork(), into a separate endpoint, configure that endpoint to receive messages on a channel, and to use configuration to achieve the multi threading in place of the executor service.
Some of the reasons we are looking at Spring Integration are as follows:
To remove the workflow logic from the code itself, so that the workflow and the chain of processing is evident on a higher level.
To simplify each class, enhancing readability and testability.
To avoid threading code if possible, and define that at a higher level of abstraction in configuration.
Given the sample code, could those goals be achieved using Spring Integration. Also, what would be an example of the DSL to achieve that.
Thanks
Something like
#Bean
public IntegrationFlow flow() {
return IntegrationFlows.from(SomeGatewayInterface.class)
.handle("someBean", "preProcess")
.channel(MessageChannels.executor(someTaskExecutorBean())
.handle("someBean", "doWork")
.get();
The argument passed to the gateway method become the payload of the preprocess method, which would return some object that becomes the message payload, which becomes the parameter passed to doWork.

Spring Integration - Service Activator - Method Signature

I have a general question. We are upgrading some old code to v4.1.3 of spring-integration. Let's say we have a service activator that receives a domain object of type Foo, and returns the same object on the output channel (after changing some properties of that object).
Our existing code has signatures like below. Is it the right convention? If I don't need the headers, can I return my payload directly and will the framework wrap it into a Message?:
public Message<Foo> computeValue(Foo payload, #Headers Map<String, Object> headerMap) {
//...
return MessageBuilder.withPayload(payload).copyHeaders(headerMap).build();
}
Yes, you don't need do that. More over that is pointless because in case of Service Activator the Framework populates request headers to the reply message independently of your effort.
So, consider do not care about headers at all if you don't need to do some specific logic on the matter.

Mock static method that calls to external service

I have a class that has a static method that passes in request and that calls server to retrieve the response.
is there a way to mock that since it unit test I do not want to make a service call.
String jsonResponse = getMeMyMoney(request)
protected static String getMeMyMoney(request)
{
response = executeService(request)
return response
}
I tried this which is supposed to bypass the method but it still went it. Any one knows how to do this
doReturn("1").when(TestClass.getMeMyMoney("S"));
You cannot mock static methods with Mockito, it is also stated in FAQ.
Use PowerMock on top of Mockito.
PowerMockito.mockStatic(TestClass.class);
when(TestClass.getMeMyMoney("S")).thenReturn("1");

What is the most concise way to get an injected bean for a springboot managed class?

I have a simple application that injects another component
#ComponentScan
#EnableAutoConfiguration
#Configuration
class Application {
static void main(String[] args) {
SpringApplication.run(Application, args)
}
#Bean
AuthorizationServerTokenServices tokenServices() {
return MY THING HERE
}
}
I'd like a quick/minimal way to new this up and grab the item springboot wires up (for tokenServices in this example). I'm trying to get at this to verify some configuration/settings/etc using TestNG
I should also say that I"m not using any xml to configure this (using gradle/groovy/springboot)
You can easily introduce conditional bean with the help of Spring profiles.
In your case the code would look like:
#Configuration
#Profile("tokenService")
public TestTokenServiceConfig {
#Primary
#Bean
AuthorizationServerTokenServices tokenServices() {
//implementation
}
}
The custom implementation you supply in this class will only be used by Spring in case the profile tokenService is active. The use of #Primary is needed in order to make Spring use the specified bean instead of any others present in the application context.
Also note that since you are going to be using the custom service in a test environment, you could easily mock the implementation using Mockito (or whatever other mocking framework you prefer)
And the actual integration test would be something like:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#ActiveProfiles("tokenService")
class YourIntegrationTest {
#Autowired
AuthorizationServerTokenServices tokenServices;
//test
}

Resources