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

查看:85
本文介绍了具有特征的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.特质的使用是什么引起了模仿的问题?

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在查看类与特征之间的关系时遇到了某种问题.猜猜这并不奇怪,因为特性不是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天全站免登陆