gpt4 book ai didi

scala - Akka 的 mock child Actor

转载 作者:行者123 更新时间:2023-12-02 03:13:18 26 4
gpt4 key购买 nike

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

这是我要测试的 Actor

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?它不应采用任何构造函数参数。

最佳答案

这是因为 MockedChild 是您测试的 child Actor 。缺少的构造函数参数是对测试(即父类)的引用。

你有三个选择:

  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
}
}
}

关于scala - Akka 的 mock child Actor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com