Pattern matching on testing expected message

前端 未结 1 1382
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-18 23:11

How can I test expected message with akka testkit if I don\'t know all message details? Can I use somehow underscore \"_\"?

Example I can test:

echoActor         


        
1条回答
  •  抹茶落季
    2021-02-18 23:35

    It doesn't look like you can do much about it, because expectMsg uses == behind the scenes.

    You could try to use expectMsgPF, where PF comes from PartialFunction:

    echoWithRandomActor ! "hi again"
    expectMsgPF() {
      case EchoWithRandom("hi again", _) => ()
    }
    

    Update

    In recent versions (2.5.x at the moment) you need a TestProbe.

    You can also return an object from the expectMsgPF. It could be the object you are pattern matching against or parts of it. This way you can inspect it further after expectMsgPF returns successfully.

    import akka.testkit.TestProbe
    
    val probe = TestProbe()
    
    echoWithRandomActor ! "hi again"
    
    val expectedMessage = testProbe.expectMsgPF() { 
        // pattern matching only
        case ok@EchoWithRandom("hi again", _) => ok 
        // assertion and pattern matching at the same time
        case ok@EchoWithRandom("also acceptable", r) if r > 0 => ok
    }
    
    // more assertions and inspections on expectedMessage
    

    See Akka Testing for more info.

    0 讨论(0)
提交回复
热议问题