将REST控制器/路由添加到SpringBoot测试

时间:2019-05-30 11:04:03

标签: spring spring-boot spring-boot-test

是否可以在SpringBoot测试中添加路由/端点(我不想将其包含在源代码中,而是将其保留在测试中)?

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

更新: 事实证明,不需要额外的配置-HelloAPI类应该从src/main移到src/test。而已。但是,它将对所有@SpringBoot测试“可见”。

所以问题是:如何将这个bean(HelloAPI)的创建(在ApplicationContext中注册)限制为特定的测试类?

See link to an example project

3 个答案:

答案 0 :(得分:1)

您可以使用@TestConfiguration

@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!";
            }
        }
    }
 }

答案 1 :(得分:0)

您可以添加用于设置Bean的静态inner scipy.py类:

@Configuration

并确保将@RunWith(SpringRunner.class) ... // Other test annotations public class YourTestClass { @Configuration static class ContextConfiguration { @Bean public HelloAPI helloAPI() { return new HelloAPI(); } } @Test public void someTest_shouldXxx() { ... } } 类添加到HelloAPI中,而不要添加/src/test

但是请注意,在执行了该类中的所有测试之后,/src/main/将被销毁,从而也将销毁(test)ApplicationContext bean。

如果您正在寻找向HelloAPI提供测试端点的方法,请将RestTemplate绑定到MockRestServiceServer instead

答案 2 :(得分:0)

尽管我已经接受了Anatoliy的回答(他们正在使用Java和JUnit5),但我还是想和我的老JUnit4共享我的Kotlin代码:

@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
class TestWithInnerConfigTest {
    @LocalServerPort var port: Int? = null
    @Autowired private lateinit var restTemplate: TestRestTemplate

    @Test
    fun testingMainEndpoint() {
        val url = "http://localhost:$port/helloworld"
        val resp = restTemplate.exchange(url, GET, null, String::class.java)
        assertEquals(resp.statusCode, OK)
    }

    @Test
    fun testingTestEndpoint() {
        val url = "http://localhost:$port/test"
        val resp = restTemplate.exchange(url, GET, null, String::class.java)
        assertEquals(resp.statusCode, NOT_FOUND)
    }

    companion object {
        @TestConfiguration
        class TestCfg {
            @RestController
            class TestApi {
                @GetMapping("/test") fun hello() = "Helloworld!"
            }
        }
    }
}

使用静态内部@TestConfiguration类的好处是它仅应用于此文件。这是link to the complete example

相关问题