简体   繁体   中英

Running Spring Cloud Contract test in non-Spring project

I have created a Spring Cloud Contract stub in a Spring Boot project ( spring-server ). The client that wants to call this stub is not a Spring project and cannot be one. If I run the following in the client:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureStubRunner(ids = {"uk.co.hadoopathome:spring-server:+:stubs:8093"},
        stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class ContractTest {
    @Test
    public void testContractEndpoint() {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet("http://localhost:8093/ac01");
            CloseableHttpResponse response = httpclient.execute(httpGet);
            String entity = EntityUtils.toString(response.getEntity());
            assertEquals("ac01returned", entity);
            response.close();
        } catch (IOException ignored) {
        }
    }
}

then I get an error

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

Obviously I don't have a @SpringBootConfiguration , as this isn't a Spring Boot project.

What's the workaround here?

Just use the Junit rule and you won't have to setup a context

public class JUnitTest {

    @Rule public StubRunnerRule rule = new StubRunnerRule()
            .downloadStub("com.example","beer-api-producer")
            .withPort(6543)
            .workOffline(true);

    @Test
    public void should_work() {
        String response = new RestTemplate().getForObject("http://localhost:6543/status", String.class);

        BDDAssertions.then(response).isEqualTo("ok");
    }

I modified the @SpringBootTest line:

@SpringBootTest(classes = ContractTest.class)

and then got some Logback errors which I resolved by finding this answer and adding to build.gradle :

configurations {
    all*.exclude module : 'spring-boot-starter-logging'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM