【问题标题】:Scala and Mockito with traits具有特征的 Scala 和 Mockito
【发布时间】:2011-09-08 18:21:30
【问题描述】:

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

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

【问题讨论】:

    标签: unit-testing scala mockito scalatest


    【解决方案1】:

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

    @Test def third_PASSES {
      val mockThird = mock[Third_B]
    
      when(mockThird.getSomething(mockA)).thenReturn(3)
    
      assert(3 === mockThird.getSomething(mockA))
    }
    

    【讨论】:

    • 我考虑直接模拟它,但它似乎不如测试整个类干净。好吧,现在已经足够好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2011-08-09
    • 2012-10-22
    相关资源
    最近更新 更多