具有特征的 Scala 和 Mockito [英] Scala and Mockito with traits

查看:25
本文介绍了具有特征的 Scala 和 Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

Mockito 是 Scala 的最佳选择吗?我是否使用了错误的工具?

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

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 在看到 class 和 trait 之间的关系时遇到了一些问题.猜猜这并不奇怪,因为特征在 Java 中不是原生的.如果您直接模拟特征本身,它会起作用,但这可能不是您想要做的?对于几种不同的特征,您需要为每个特征创建一个模拟:

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:

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

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

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

这篇关于具有特征的 Scala 和 Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆