【问题标题】:Mocking child actor in Akka在 Akka 中嘲笑儿童演员
【发布时间】:2016-07-30 16:44:55
【问题描述】:

我正在尝试为我的演员编写单元测试,但我被困在基本的模拟上。 PriceAggregateActor 正在使用 akka 持久性,我不想为它传递所有的 conf,而是想完全模拟它。

这是我要测试的演员

object CommandPriceActor {
  def apply() = Props(classOf[CommandPriceActor], PriceAggregateActor())
}

class CommandPriceActor(priceAggregateActorProps: Props) extends Actor with ActorLogging {

  val priceAggregateActor = context.actorOf(priceAggregateActorProps, "priceAggregateActor")

所以在我的测试中,我正在尝试做类似的事情:

class CommandPriceActorTest extends TestKit(ActorSystem("test-benefits",
  ConfigFactory.parseString("""akka.loggers = ["akka.testkit.TestEventListener"] """))) with FlatSpecLike with Matchers
  with BeforeAndAfterAll with Eventually{

  class MockedChild extends Actor {
    def receive = {
      case _ => lala
    }
  }

  val probe = TestProbe()
  val commandPriceActor = TestActorRef(new CommandPriceActor(Props[MockedChild]))

我总是得到:

Caused by: java.lang.IllegalArgumentException: no matching constructor found on class CommandPriceActorTest$MockedChild for arguments []

为什么抱怨 mockedChild?它不应该接受任何构造函数参数。

【问题讨论】:

    标签: scala unit-testing akka akka-testkit


    【解决方案1】:

    这是因为 MockedChild 是您测试的子角色。缺少的构造函数参数是对测试(它是父类)的引用。

    您有三个选择:

    1. 将对this 的引用传递给Props
    2. 使用Props的命名参数形式
    3. 使 MockedChild 成为顶级类(或对象的成员)

    选项 1

    val probe = TestProbe()
    val mockProps = Props(classOf[MockedChild], this)
    val commandPriceActor = TestActorRef(new CommandPriceActor(mockProps))
    

    选项 2

    val probe = TestProbe()
    val mockProps = Props(new MockedChild)
    val commandPriceActor = TestActorRef(new CommandPriceActor(mockProps))
    

    选项 3

    val probe = TestProbe()
    val mockProps = Props(new CommandPriceActorTest.MockedChild)
    val commandPriceActor = TestActorRef(new CommandPriceActor(mockProps))
    
    // ....
    
    object CommandPriceActorTest {
      class MockedChild extends Actor {
        def receive = {
          case _ => lala
        }
      }
    }
    

    【讨论】:

    • 我明白你在说什么,但我该如何用代码编写呢? :)
    • 我添加了一些示例。最初的答案是在机场用我的手机做出的。
    • 像魅力一样工作!谢谢伊恩:)
    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多