testcontainers的Localstack模块未运行用于集成测试

时间:2019-09-27 04:56:53

标签: java spring-boot testcontainers localstack

我正在尝试为Spring启动服务进行一些整合测试。由于该服务使用的是AWS SQS和DynamoDB,因此我倾向于利用testcontainer的Localstack模块进行集成测试。但是,尽管我认为我已经包含了所有必需的代码,但是LocalStackContainer似乎没有运行,并且引发了以下错误:

com.amazonaws.SdkClientException: Unable to execute HTTP request: Connect to localhost:4576
  [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)

顺便说一句,如果我使用独立的本地堆栈(即在终端“ $ localstack start”中手动运行),则集成测试将通过。

有人可以帮我弄清楚我所缺少的吗?

在build.gradle中,我有

testCompile("org.testcontainers:testcontainers:1.10.6")
testCompile("org.testcontainers:localstack:1.10.6")

在超级类中,我设置了一些共享的测试上下文,例如LocalStackContainer作为@ClassRule

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("local")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@Slf4j
public class BaseIntegrationTest extends CamelTestSupport {

    @Value("${isLocal:false}")
    protected boolean isLocal;

    @Value("${isLocalStack:true}")
    protected boolean isLocalStack;

    @Value("${instanceUrl}")
    protected String instanceUrl;

    @LocalServerPort
    private int serverPort;

    @EndpointInject(uri = "mock:endPoint")
    protected MockEndpoint mockEndpoint;

    protected ApplicationContext appContext;
    protected AmazonDynamoDB amazonDynamoDB;
    protected AmazonSQS amazonSQS;
    protected CamelContext camelContext;
    protected Exchange exchange;
    protected ProducerTemplate producerTemplate;

    @ClassRule
    public static LocalStackContainer localstack = new LocalStackContainer()
            .withEnv("HOSTNAME_EXTERNAL", DockerClientFactory.instance().dockerHostIpAddress())
            .withExposedPorts(4569, 4576) // mock DynamoDB (http port 4569), mock SQS (http port 4576)
            .withStartupAttempts(3)
            .withStartupTimeout(Duration.ofMinutes(3))
            .withServices(DYNAMODB, SQS);

    @BeforeClass
    public static void init() {
        localstack.start();
    }

    @AfterClass
    public static void teardown() {
        localstack.stop();
    }

    @Before
    public void setup() throws Exception {
        RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
        RestAssured.port = serverPort;

        if (instanceUrl != null) {
            RestAssured.baseURI = instanceUrl;
        } else {
            RestAssured.requestSpecification = new RequestSpecBuilder()
                    .setBaseUri(System.getProperty("APP_HOST", "http://localhost:" + serverPort))
                    .build();
        }

        String dynamoDBEndpoint = "http://" + localstack.getContainerIpAddress() 
                                            + ":" + localstack.getMappedPort(4569);
        String sqsEndpoint = "http://" + localstack.getContainerIpAddress() 
                                       + ":" + localstack.getMappedPort(4576);

        log.info("The integration test is using localstack dynamoDBEndpoint={} and sqsEndpoint={}",
                dynamoDBEndpoint, sqsEndpoint);

        appContext = new SpringApplicationBuilder(Application.class)
                .profiles("local")
                .properties("localstackDynamoDBEndpoint=" + dynamoDBEndpoint,
                        "localstackSQSEndpoint=" + sqsEndpoint)
                .run();

        amazonDynamoDB = appContext.getBean(AmazonDynamoDB.class);
        amazonSQS = appContext.getBean(AmazonSQS.class);
        camelContext = appContext.getBean(CamelContext.class);
        producerTemplate = camelContext.createProducerTemplate();
    }

    @After
    public void cleanup() {
        ((ConfigurableApplicationContext) appContext).close();
    }

}

在扩展超类的测试类中,这只是一些令人放心的代码

@Test
public void test400Response() {

    given()
            .body("")
            .contentType("application/json")
            .post("/root/my_service/v1")
            .then()
            .statusCode(HttpStatus.SC_BAD_REQUEST)
            .body("message", Matchers.equalTo("Missing expected content"))
            .log()
            .all();
}

如果您想看一看,这是成功测试的日志

https://justpaste.it/success-with-running-localstack

以及失败测试的日志

https://justpaste.it/failed-with-localstackContainer

1 个答案:

答案 0 :(得分:0)

我不再使用测试容器,而是使用 Dockercompose。这就是我现在用 Gradle 做的事情。

在 build.gradle 中添加

apply from: file('gradle/integration.gradle')

然后在gradle文件夹的integration.gradle文件中添加

apply plugin: 'docker-compose'

dockerCompose {
    useComposeFiles = ["${rootDir}/localstack/docker-compose.yml"]
}

并定义一个integrationTest任务

task integrationTest (type: Test) { 
 //....
}

使用适当的 docker-compose.yml 包括 Localstack docker 图像和 gradle 文件中的其他内容,我可以成功运行此

./gradlew clean integrationTest
相关问题