我想为foreach ($data[0] as $key => $value) {
// dd($value->name);
$insert[] = [
'name' => $value->name,
'email' => $value->email,
'phone' => $value->phone,
];
}
项目设置测试环境。另外,我需要启动在Docker容器中运行的Kafka。
在开始测试之前,应先启动Kafka容器。
我正在使用Scalatest,并打算在测试运行之前一次在TestFixture中启动Kafka容器。
问题是,这是在运行测试之前启动容器的推荐方法。我考虑过Docker API,但不确定,这是否正确。
答案 0 :(得分:3)
您可以使用testcontainers-scala,它只是testcontainers的包装。
在您的build.sbt
中添加:
libraryDependencies += "com.dimafeng" %% "testcontainers-scala" % "0.25.0" % "test"
libraryDependencies += "org.apache.kafka" % "kafka-clients" % "2.2.0"
然后您可以创建规范:
import com.dimafeng.testcontainers.{ForAllTestContainer, GenericContainer}
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer}
import org.scalatest.FlatSpec
import org.testcontainers.containers.Network
import org.testcontainers.utility.Base58
class KafkaSpec extends FlatSpec with ForAllTestContainer {
final val KafkaPort = 9093
override val container = GenericContainer("confluentinc/cp-kafka").configure{ c =>
c.withNetwork(Network.newNetwork())
c.withNetworkAliases("kafka-" + Base58.randomString(6))
c.withExposedPorts(KafkaPort)
c.withEnv("KAFKA_LISTENERS", "PLAINTEXT://0.0.0.0:" + KafkaPort + ",BROKER://0.0.0.0:9092")
c.withEnv("KAFKA_LISTENER_SECURITY_PROTOCOL_MAP", "BROKER:PLAINTEXT,PLAINTEXT:PLAINTEXT")
c.withEnv("KAFKA_INTER_BROKER_LISTENER_NAME", "BROKER")
c.withEnv("KAFKA_BROKER_ID", "1")
c.withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1")
c.withEnv("KAFKA_OFFSETS_TOPIC_NUM_PARTITIONS", "1")
c.withEnv("KAFKA_LOG_FLUSH_INTERVAL_MESSAGES", Long.MaxValue.toString)
c.withEnv("KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS", "0")
}
it should "do something" in {
val properties = new Properties()
properties.put("bootstrap.servers", s"${container.containerIpAddress}:$KafkaPort")
properties.put("group.id", "test")
properties.put("key.deserializer", classOf[StringDeserializer])
properties.put("value.deserializer", classOf[StringDeserializer])
properties.put("key.serializer", classOf[StringSerializer])
properties.put("value.serializer", classOf[StringSerializer])
val kafkaConsumer = new KafkaConsumer[String, String](properties)
....
}
}