gpt4 book ai didi

unit-testing - Scala 和 Mockito 的特征

转载 作者:行者123 更新时间:2023-12-04 11:59:33 26 4
gpt4 key购买 nike

我有一个简单的类,它自然分为两部分,所以我重构为

class Refactored extends PartOne with PartTwo

然后单元测试开始失败。

下面是重新创建问题的尝试。所有三个示例的功能都相同,但第三个测试失败,并显示 NullPointerException。导致 mockito 问题的特征的使用是什么?

编辑: Mockito 是 Scala 的最佳选择吗?我是否使用了错误的工具?
import org.scalatest.junit.JUnitSuite
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito.when
import org.junit.Test
import org.junit.Before

class A(val b:B)
class B(val c:Int)

class First(){
def getSomething(a:A) = a.b.c
}

class Second_A extends Second_B
class Second_B{
def getSomething(a:A) = a.b.c
}

class Third_A extends Third_B
trait Third_B{
// Will get a NullPointerException here
// since a.b will be null
def getSomething(a:A) = a.b.c
}

class Mocking extends JUnitSuite with MockitoSugar{
var mockA:A = _
@Before def setup { mockA = mock[A] }

@Test def first_PASSES {
val mockFirst = mock[First]
when(mockFirst.getSomething(mockA)).thenReturn(3)

assert(3 === mockFirst.getSomething(mockA))
}

@Test def second_PASSES {
val mockSecond = mock[Second_A]
when(mockSecond.getSomething(mockA)).thenReturn(3)

assert(3 === mockSecond.getSomething(mockA))
}

@Test def third_FAILS {
val mockThird = mock[Third_A]

//NullPointerException inside here (see above in Third_B)
when(mockThird.getSomething(mockA)).thenReturn(3)

assert(3 === mockThird.getSomething(mockA))
}
}

最佳答案

似乎 Mockito 在看到类和特征之间的关系时遇到了一些问题。猜猜这并不奇怪,因为特征不是 Java 原生的。如果您直接模拟特征本身,它会起作用,但这可能不是您想要做的?有几个不同的特征,你需要一个模拟:

@Test def third_PASSES {
val mockThird = mock[Third_B]

when(mockThird.getSomething(mockA)).thenReturn(3)

assert(3 === mockThird.getSomething(mockA))
}

关于unit-testing - Scala 和 Mockito 的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6243467/

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