为什么Mockito没有正确处理默认的Scala参数?

时间:2015-10-06 16:50:17

标签: scala mockito scalatest

我有像

这样的代码
  test("mockito test") {
    class ToTest {
      def run(maybe: Option[Int], q: Option[Int] = None): Int = 42
    }

    val mockTest = mock[ToTest]
    when(mockTest.run(None, None)).thenReturn(98)
    mockTest.run(None)
    verify(mockTest, times(1)).run(None, None)
  }

哪个失败

[info] - mockito test *** FAILED ***
[info]   org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:
[info] toTest$1.run(None, None);
[info] -> at xxx$$anonfun$3.apply$mcV$sp(xxx.scala:55)
[info] Actual invocation has different arguments:
[info] toTest$1.run(None, null);

或另一种情况

  test("mockito test") {
    class ToTest {
      def run(maybe: Option[Int], q: Int = 5): Int = 42
    }

    val mockTest = mock[ToTest]
    when(mockTest.run(None, 5)).thenReturn(101)
    mockTest.run(None)
    verify(mockTest, times(1)).run(None, 5)
  }

失败
[info] - mockito test *** FAILED ***
[info]   org.mockito.exceptions.verification.junit.ArgumentsAreDifferent: Argument(s) are different! Wanted:
[info] toTest$1.run(None, 5);
[info] -> at xxx$$anonfun$3.apply$mcV$sp(xxx.scala:55)
[info] Actual invocation has different arguments:
[info] toTest$1.run(None, 0);

我想这是因为Java中没有默认参数。它有什么解决方法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

我想这是因为CGLIB(或2.0 beta版本的Byte Buddy)在这种情况下生成代码,而不是Scala编译器,因此默认参数将始终为null

解决方法可能(至少在某些情况下)使用spy代替:

val mockTest = spy(classOf[ToTest])

很抱歉,ScalaTest中没有糖语法。