Scala和Mockito有特征

时间:2011-06-05 14:19:07

标签: unit-testing scala mockito scalatest

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

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))
    }
}

1 个答案:

答案 0 :(得分:6)

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

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

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

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