简体   繁体   English

在单元测试中验证 akka-stream 源

[英]Validating akka-stream Source in unit test

What is idiomatic way of validating a akka-stream Source in a unit test?在单元测试中验证 akka-stream Source 的惯用方法是什么? I am doing like this:我正在这样做:

f.service.fetchData(id).flatMap {
          case Right(source) => {
            // TODO: I need to validate here that source contains "Test value"
          }
          case Left(_) => fail("Wrongly responded with error")
        }

source is basically:来源基本上是:

Source.single(ByteString("Test value"))

I tried to execute by connecting Source to a Sink and checking the emitted values, but assertions don't seem to work.我尝试通过将 Source 连接到 Sink 并检查发出的值来执行,但断言似乎不起作用。

The correct way of testing Sources, Flows and Sinks is by using test probes .测试 Sources、Flows 和 Sinks 的正确方法是使用测试探针

Imagine you have following source and you'd like to test its logic假设您有以下来源,并且您想测试其逻辑

val source = Source(Seq("TestValue")).collect {
  case s @ "TestValue" => Right[String, String](s)
  case _               => Left[String, String]("error")
}

(I know that Left will never trigger here but it's just an example) (我知道Left永远不会在这里触发,但这只是一个例子)

Now, you can define a TestSink that is connected to the given source.现在,您可以定义一个连接到给定源的TestSink The resulting grapth is run in the following way.生成的图形按以下方式运行。

"assert correct value" in {
  implicit val system: ActorSystem = ???
  val probe = source.toMat(TestSink.probe)(Keep.right).run()
  probe.request(1)
  probe.expectNext(Right("TestValue"))
}

TestSink.probe is a sink that materializes into a TestSubscriber.Probe[T] and it provides controls over the stream. TestSink.probe是一个实现为TestSubscriber.Probe[T]的接收器,它提供对 stream 的控制。 Since it's a sink, it needs to emit demand for an element.由于它是一个接收器,它需要发出对元素的需求。 It does it via request(1) or request one element.它通过request(1)或请求一个元素来完成。 Then it's followed by assert sink.expectNext(Right("TestValue")) that checks that correct value is received.然后是 assert sink.expectNext(Right("TestValue"))检查是否收到了正确的值。

There is also a counterpart called TestSource.probe that allows testing of any Sink .还有一个名为TestSource.probe的对应项允许测试任何Sink

And by combing both of them, you can test any Flow .通过结合它们,您可以测试任何Flow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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