Search code examples
spock

How to access application.yml file from the spock test framework


I have integration tests being configured for a spring boot application which interacts with downstream services. I would like to configure some of the variables used in the spock tests from the application.yml that is used in the spring application. Is this possible in Spock and groovy.

I have tried using Spring annotations to capture the data as its done in the Spring application.

I have tried using the below code but it always is null.

@Value('test.base.url')
def variableName

I also tried to pointing to the application.yml using the @PropertySource('classpath:application.yml')

package com.company.package1

import groovyx.net.http.RESTClient
import org.junit.experimental.categories.Category
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.context.ContextConfiguration
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll

@ContextConfiguration(classes = Application.class)
@Category(IntegrationTest.class)
class GetVariableTests extends Specification {

    @Value('test.base.url')
    def variableName

    def "test variable name"() {
        then:
            variableName == "http://localhost:8020/"
    }
}

application.yml

test:
   base:
       url:"http://localhost:8020/"

I would want this test to pass. However the variableName is always null.


Solution

  • Your Spec looks incomplete, a single then: block is not a valid test for Spock. If you want something like that you need expect:.

    Also this looks like a Spring Boot project, if so you should use @SpringBootTest instead of @ContextConfiguration. Also make sure you have the spock-spring dependency.