ClassCastException 在 Scala 中使用 ArgumentCapture 进行 Double [英] ClassCastException using ArgumentCapture for Double in scala

查看:15
本文介绍了ClassCastException 在 Scala 中使用 ArgumentCapture 进行 Double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 scala 中使用 ArgumentCapture 作为 Double 时遇到问题.我正在尝试将 Double 参数捕获到模拟特征.尝试捕获 Int 时,相同的语法可以正常工作.

I'm having a problem using ArgumentCapture for a Double in scala. I'm trying to capture a Double argument to a mocked trait. The same syntax works fine when trying to capture an Int.

这是一个示例测试:

import org.scalatest.FunSuite
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
import org.mockito.ArgumentCaptor

trait MockedTrait {
    def mockedDoubleMethod(double: Double)
    def mockedIntegerMethod(integer: Int)
}

class ClassUnderTest(myTrait: MockedTrait) {
    def methodUnderTest {
        myTrait.mockedIntegerMethod(3)
        myTrait.mockedDoubleMethod(5.0)
    }
}

class MyTest extends FunSuite with MockitoSugar {

    test("A basic test") {
        val myTrait = mock[MockedTrait]

        val classUnderTest = new ClassUnderTest(myTrait)
        classUnderTest.methodUnderTest

        val capturedInteger = ArgumentCaptor.forClass(classOf[Int])
        verify(myTrait).mockedIntegerMethod(capturedInteger.capture)

        val capturedDouble = ArgumentCaptor.forClass(classOf[Double])
        verify(myTrait).mockedDoubleMethod(capturedDouble.capture) // Throws ClassCastException
    }

}

我得到以下异常:

java.lang.Integer cannot be cast to java.lang.Double
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
    at scala.runtime.BoxesRunTime.unboxToDouble(Unknown Source)
    at MyTest$$anonfun$1.apply$mcV$sp(MyTest.scala:30)
    at MyTest$$anonfun$1.apply(MyTest.scala:20)
    at MyTest$$anonfun$1.apply(MyTest.scala:20)
    at org.scalatest.FunSuite$$anon$1.apply(FunSuite.scala:1265)
    at org.scalatest.Suite$class.withFixture(Suite.scala:1968)
    at MyTest.withFixture(MyTest.scala:18)

有什么建议吗?

推荐答案

我也遇到了类似的问题.我相信这应该可以解决它:

I had similar problem. This should fix it I believe:

val capturedDouble = ArgumentCaptor.forClass(classOf[java.lang.Double])

这篇关于ClassCastException 在 Scala 中使用 ArgumentCapture 进行 Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆