Scala 和 Mockito 的特征

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6243467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:04:12  来源:igfitidea点击:

Scala and Mockito with traits

unit-testingscalamockitoscalatest

提问by Pengin

I had a simple class that naturally divided into two parts, so I refactored as

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

class Refactored extends PartOne with PartTwo

Then the unit tests started failing.

然后单元测试开始失败。

Below is an attempt to recreate the problem. The functionality of all three examples is the same, but the third test fails with a NullPointerException as indicated. What it is about the use of traits that is causing the problem with mockito?

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

Edit:Is Mockito the best choice for Scala? Am I using the wrong tools?

编辑: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))
    }
}

采纳答案by eivindw

Seems Mockito has some kind of problem seeing the relationship between class and trait. Guess this is not that strange since traits are not native in Java. It works if you mock the trait itself directly, but this is maybe not what you want to do? With several different traits you would need one mock for each:

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

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

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

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