Integration Test with Spring Boot and Spock

后端 未结 4 1760
天涯浪人
天涯浪人 2020-12-02 11:10

What is the best way to run an integration test (e.g., @IntegrationTest) with Spock? I would like to bootstrap the whole Spring Boot application and execute some HTTP calls

4条回答
  •  爱一瞬间的悲伤
    2020-12-02 12:10

    Here is a setup which starts up boot applicaiton and then runs spock tests:

    class HelloControllerSpec extends Specification {
    
    @Shared
    @AutoCleanup
    ConfigurableApplicationContext context
    
    void setupSpec() {
        Future future = Executors
                .newSingleThreadExecutor().submit(
                new Callable() {
                    @Override
                    public ConfigurableApplicationContext call() throws Exception {
                        return (ConfigurableApplicationContext) SpringApplication
                                .run(Application.class)
                    }
                })
        context = future.get(60, TimeUnit.SECONDS)
    }
    
    void "should return pong from /ping"() {
        when:
        ResponseEntity entity = new RestTemplate().getForEntity("http://localhost:8080/ping", String.class)
    
        then:
        entity.statusCode == HttpStatus.OK
        entity.body == 'pong'
    }
    }
    

    And remember to add dependencies to spock and groovy inside build.gradle

    dependencies {
        // other dependencies
        testCompile "org.codehaus.groovy:groovy-all:2.2.0"
        testCompile "org.spockframework:spock-core:0.7-groovy-2.0"
    }
    

提交回复
热议问题