Search code examples
springspring-bootspring-boot-test

Add REST controller/route to SpringBoot test


Is it possible to add a route/endpoint (which I don't want to include in the sources, but rather leave it in the tests) to a SpringBoot test?

@RestController
class HelloAPI {
    @GetMapping("/hello")
    public String ok() {
        return "world";
    }
}

UPDATE: As it turned out no extra configuration is needed - HelloAPI class should be moved from src/main to src/test. That's it. However, it will be "visible" to all @SpringBoot tests.

So the question is: how can I restrict the creation (registration in the ApplicationContext) of this bean (HelloAPI) to a particular test class?

See link to an example project


Solution

  • You can use the @TestConfiguration for this:

    @ExtendWith(SpringExtension.class)
    @SpringBootTest(webEnvironment = DEFINED_PORT)
    class EmbeddedApiTest {
    
        @Test
        void testSomething() {
            ...
        }
    
        @TestConfiguration
        public static class TestCfg {
    
            @RestController
            @RequestMapping("/test")
            public class TestApi {
    
                @GetMapping("/hello")
                public String hello() {
                    return "Hello World!";
                }
            }
        }
     }