Search code examples
spring-integrationspring-integration-dsl

How to write the JUnit for the Spring Integration DSL Http.outboundGateway operation


How to write the JUnit for the following Spring Integration DSL Http.outboundGateway operation:

    integrationFlowBuilder
       .from(integerMessageSource(),
            c -> c.poller(Pollers.cron("0 0/1 * 1/1 * ?")
       .handle(Http
            .outboundGateway("http://localhost:8050/greeting")
            .httpMethod(HttpMethod.GET)
            .expectedResponseType(String.class))
       .channel("getChannel");

    flowContext.registration(integrationFlowBuilder.get()).register();

The integerMessageSource method is

    @Bean
    private MethodInvokingMessageSource integerMessageSource() {
        final MethodInvokingMessageSource source = new MethodInvokingMessageSource();
        source.setObject(new AtomicInteger());
        source.setMethodName("getAndIncrement");
        return source;
    }

I want to start the JUnit with some cron expression and verify that the URL "http://localhost:8050/greeting" is called. It would be good that the server in the URL http://localhost:8050/greeting would be mocked so that it responds some response.

With the POST operation I want to check that some JSON is sent to the URL http://localhost:8050/greeting.

Is this possible to test?


Solution

  • For testing REST on the client side the Spring Test Framework provides this:

    /**
     * <strong>Main entry point for client-side REST testing</strong>. Used for tests
     * that involve direct or indirect use of the {@link RestTemplate}. Provides a
     * way to set up expected requests that will be performed through the
     * {@code RestTemplate} as well as mock responses to send back thus removing the
     * need for an actual server.
     *
     * <p>Below is an example that assumes static imports from
     * {@code MockRestRequestMatchers}, {@code MockRestResponseCreators},
     * and {@code ExpectedCount}:
     *
     * <pre class="code">
     * RestTemplate restTemplate = new RestTemplate()
     * MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build();
     *
     * server.expect(manyTimes(), requestTo("/hotels/42")).andExpect(method(HttpMethod.GET))
     *     .andRespond(withSuccess("{ \"id\" : \"42\", \"name\" : \"Holiday Inn\"}", MediaType.APPLICATION_JSON));
     *
     * Hotel hotel = restTemplate.getForObject("/hotels/{id}", Hotel.class, 42);
     * &#47;&#47; Use the hotel instance...
     *
     * // Verify all expectations met
     * server.verify();
     * </pre>
     *
     * <p>Note that as an alternative to the above you can also set the
     * {@link MockMvcClientHttpRequestFactory} on a {@code RestTemplate} which
     * allows executing requests against an instance of
     * {@link org.springframework.test.web.servlet.MockMvc MockMvc}.
     *
     * @author Craig Walls
     * @author Rossen Stoyanchev
     * @since 3.2
     */
    @SuppressWarnings("deprecation")
    public final class MockRestServiceServer {
    

    The Http.outboundGateway() can be configured with the RestTemplate and this one has to be used for that MockRestServiceServer. Something like this:

    @ContextConfiguration
    @RunWith(SpringJUnit4ClassRunner.class)
    @DirtiesContext
    public class OutboundResponseTypeTests {
    
        @Autowired
        private RestTemplate restTemplate;
    
            private MockRestServiceServer mockServer;
    
        @Before
        public void setup() {
            this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
        }
    
        @Test
        public void testDefaultResponseType() throws Exception {
            this.mockServer.expect(requestTo("/testApps/outboundResponse"))
                    .andExpect(method(HttpMethod.POST))
                    .andRespond(withSuccess(HttpMethod.POST.name(), MediaType.TEXT_PLAIN));
    
            ...
    
            this.mockServer.verify();
        }
    
    }
    

    See Doc for more information: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#spring-mvc-test-client