2011-06-05 27 views
5

我做了一个简单的类,自然地分成两个部分,所以我重构为Scala和使用的Mockito性状

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

回答

4

似乎Mockito在看到阶级和特质之间的关系时存在某种问题。猜猜这并不奇怪,因为特征在Java中不是原生的。如果你直接嘲笑这个特质本身,它可以工作,但这可能不是你想要做的事情?有几个不同的特点,你将需要一个模拟每个:

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

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

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

我认为直接嘲笑它,但它似乎比测试整体班干净。那么,现在已经够好了。 – Pengin 2011-06-06 21:34:14