【问题标题】:Scala problem with jMock expectations and returning a value from mockScala 问题与 jMock 期望并从模拟返回值
【发布时间】:2010-07-08 22:03:10
【问题描述】:

已解决。 IntelliJ 没有强调我的导入不完整这一事实。

嗨,

我有一个简单的 Scala 程序,我正在尝试使用 jMock 进行开发。设置基本期望效果很好,但出于某种原因,Scala 不理解我从模拟对象返回值的尝试。我的 maven 构建喷出以下错误

TestLocalCollector.scala:45: error: not found: value returnValue
one (nodeCtx).getParameter("FilenameRegex"); will( returnValue(regex))
                                                   ^

而各自的代码sn-ps是

@Before def setUp() : Unit = { nodeCtx = context.mock(classOf[NodeContext]) }
...
// the value to be returned
val regex = ".*\\.data"
...
// setting the expectations
one (nodeCtx).getParameter("FilenameRegex"); will( returnValue(regex))

在我看来,Scala 期望静态 jMock 方法 returnValue 会是 val?我在这里错过了什么?

【问题讨论】:

  • 你能在评论中留下你最终使用的正确语法吗?我将在下面的答案中包含它。
  • 这里是相关部分,returnValue 静态方法不可见,因此出现错误。而will 方法只记录最新模拟操作的动作,这就是为什么它可以在下一行或分号之后:) import org.jmock.Expectations import org.jmock.Expectations._ ... context。检查(新期望 {{ oneOf (nodeCtx).getParameter("FilenameRegex") will( returnValue(".*\\.data") ) }})
  • 谢谢。然后是范围问题。使用正确的导入,它会更好地工作。答案已更新。

标签: scala jmock


【解决方案1】:

您确定“;”吗?

one (nodeCtx).getParameter("FilenameRegex") will( returnValue(regex))

可能会更好。

this example 中,您会看到如下一行:

  expect {
    one(blogger).todayPosts will returnValue(List(Post("...")))
  }

带有以下评论:

通过将“will”定义为 Scala 中缀运算符来指定在同一表达式中的返回值。
在 Java 等效项中,我们必须进行单独的方法调用(我们最喜欢的 IDE 可能坚持这样做)放在下一行!)

  one(blogger).todayPosts; will(returnValue(List(Post("..."))))
                         ^
                         |
                         -- semicolon only in the *Java* version

OP 自己解释:

returnValue 静态方法不可见,因此出现错误。
will 方法只是记录最近一次模拟操作的动作,这就是为什么它可以在下一行或分号之后:)

import org.jmock.Expectations 
import org.jmock.Expectations._ 
... 
context.checking( 
  new Expectations {
    { oneOf (nodeCtx).getParameter("FilenameRegex") will( returnValue(".*\\.data") ) }
  }
) 

【讨论】:

  • 嗯,分号是剩下的,删除了,但现在我明白了error: value will is not a member of java.lang.String
  • @puudeli:这很正常,will 接受 jMock 操作,例如 returnValue。不是字符串。
  • 错误指向 mock 对象:one (nodeCtx).getParameter("FilenameRegex") will returnValue(regex) getParameter 方法返回一个字符串,因此 scala 编译器将 will 附加到 ret val
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多