单元测试Kafka Streams与MockedStreams失败,简单的mapValues以大写形式转换

时间:2018-03-30 07:12:39

标签: string scala unit-testing apache-kafka apache-kafka-streams

我正在尝试使用MockedStreams库对Kafka Stream进行单元测试。

为了测试一个简单的例子,我只想将字符串转换为大写

我尝试下面的代码:

import com.madewithtea.mockedstreams.MockedStreams
import org.apache.kafka.common.serialization.Serdes
import org.scalatest.{Matchers, WordSpec}

class mockedStreamsSpec extends WordSpec with Matchers {

  val input = Seq(("x", "foo"), ("y", "bar"))
  val exp = Seq(("x", "FOO"), ("y", "BAR"))

  "Put in upper case " should {
    "always return value in upper case" in {
      MockedStreams()
        .topology {
          builder =>
            builder.stream[String, String]("topic-in")
              .mapValues[String](_.toUpperCase())
              .to("topic-out")
        }
        .input("topic-in", Serdes.String(), Serdes.String(), input)
        .output("topic-out", Serdes.String(), Serdes.String(), exp.size) shouldEqual exp
    }
  }
}

我收到错误了java.lang.String

[info] mockedStreamsSpec:
[info] Put in upper case
[info] - should always return value in upper case *** FAILED ***
  [info]   java.lang.ClassCastException: [B cannot be cast to java.lang.String
  [info]   at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:40)
[info]   at org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:46)
[info]   at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:208)
[info]   at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:124)
[info]   at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:85)
[info]   at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:80)
[info]   at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:216)
[info]   at org.apache.kafka.test.ProcessorTopologyTestDriver.process(ProcessorTopologyTestDriver.java:276)
[info]   at org.apache.kafka.test.ProcessorTopologyTestDriver.process(ProcessorTopologyTestDriver.java:315)
[info]   at com.madewithtea.mockedstreams.MockedStreams$Builder.$anonfun$produce$1(MockedStreams.scala:110)

看起来很奇怪,因为Scala String和Java String应该完全相同。

1 个答案:

答案 0 :(得分:1)

我从未使用过这个MockedStreams库,但异常" [B不能转换为java.lang.String"表示正在将字节数组强制转换为String。我建议你尝试使用builder.stream()方法的变体(在拓扑结构中),它允许你明确指定要使用的Serdes,因为它接缝给input()方法没有被使用。我想这些只用于将测试数据序列化到流上。