我有一个简单的类,自然分为两部分,所以我重构为
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))
}
}
答案 0 :(得分:6)
@Test def third_PASSES {
val mockThird = mock[Third_B]
when(mockThird.getSomething(mockA)).thenReturn(3)
assert(3 === mockThird.getSomething(mockA))
}