单元测试 – Scala和Mockito具有特征
发布时间:2020-12-16 18:37:39 所属栏目:安全 来源:网络整理
导读:我有一个简单的类,自然分为两部分,所以我重构为 class Refactored extends PartOne with PartTwo 然后单元测试开始失败. 下面是尝试重现问题.所有三个示例的功能都相同,但第三个测试失败并显示NullPointerException.什么是使用导致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)) } } 解决方法
看起来Mockito在看到阶级和特质之间的关系时遇到了一些问题.猜猜这并不奇怪,因为特征在Java中不是原生的.它可以直接模拟特征本身,但这可能不是你想要做的?有几个不同的特征,你需要一个模拟:
@Test def third_PASSES { val mockThird = mock[Third_B] when(mockThird.getSomething(mockA)).thenReturn(3) assert(3 === mockThird.getSomething(mockA)) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |