因此,我正在尝试使用Mockito为我的Hadoop映射功能创建一个单元测试。我已经正确创建了映射类:
class XmlMapper extends Mapper[LongWritable, Text, Text, LongWritable] {
override def map(key: LongWritable, value: Text, context: Mapper[LongWritable, Text, Text, LongWritable]#Context): Unit = {
//does stuff
}
}
然后我有以下测试:
import org.apache.hadoop.io.{LongWritable, Text}
import org.scalatest.FlatSpec
import org.scalatest.mockito.MockitoSugar
import org.mockito.Mockito.verify
import org.mockito.Mockito.times
class XmlMapperTest extends FlatSpec with MockitoSugar {
"XmlMapper" should "output" in {
val mapper = new XmlMapper
val context = mock[mapper.Context]
//so far does nothing yet
}
}
但是我会收到以下错误:
- should output *** FAILED ***
[info] org.mockito.exceptions.base.MockitoException: Mockito cannot mock this class: class org.apache.hadoop.mapreduce.Mapper$Context.
[info]
[info] Mockito can only mock non-private & non-final classes.
[info] If you're not sure why you're getting this error, please report to the mailing list.
这是没有意义的,因为mapper.context是公共抽象类。
这是总堆栈跟踪:
[info] Underlying exception : java.lang.UnsupportedOperationException: Cannot define class using reflection
[info] at org.scalatest.mockito.MockitoSugar.mock(MockitoSugar.scala:73)
[info] at org.scalatest.mockito.MockitoSugar.mock$(MockitoSugar.scala:72)
[info] at XmlMapperTest.mock(XmlMapperTest.scala:7)
[info] at XmlMapperTest.$anonfun$new$1(XmlMapperTest.scala:11)
[info] at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[info] at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
[info] at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
[info] at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
[info] at org.scalatest.Transformer.apply(Transformer.scala:22)
[info] at org.scalatest.Transformer.apply(Transformer.scala:20)
看来您正在使用旧版本的莫科托核,鉴于您使用的是Scala,我强烈建议您转到最新版本的Mockito-Scala
另外,只要可能,作为一个好练习,您应该避免嘲笑自己不拥有的课程。一种更好的方法是将与第三方的互动(或一组课程)包裹起来,并进行集成测试以证明它们按预期工作。
在系统的其余部分中,您注入了这些类,因此,对于测试,您嘲笑了所说的类,这使您可以控制(并简化)裸露的接口,并在第三章的未来版本中最大程度地减少破坏政党lib更改其API。
有关更多详细信息,请查看此stackoverflow答案以及Mockito Blog上的这篇文章