无效使用参数匹配器 0 匹配预期。 3 记录

Invalid use of argument matchers 0 matches expected. 3 recorded

我正在使用 MockitoSugar 在 scala 中编写单元测试。我正在使用 org.mockito.Mockito.whenorg.mockito.Matchers.anyString。被测方法如下图

def getDataSourceToDataFrame(database: scala.Predef.String, tableName: scala.Predef.String): DataFrame = {
glueContext.getCatalogSource(
  database = database,
  tableName = tableName,
  transformationContext = database + "." + tableName + ".read")
  .getDynamicFrame()
  .toDF()

}

这是我的单元测试的样子:

import com.amazon.rrsetlglue.glue.wrappers.WrappedGlueContext
import com.amazonaws.services.glue.{DynamicFrame, GlueContext, DataSource}
import org.scalatest.{BeforeAndAfter, FunSuite, Matchers}
import org.apache.spark.sql.DataFrame
import org.mockito.Mockito.when
import org.mockito.Matchers.anyString
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
// Use Mockito because ScalaMock does not work with Glue
@RunWith(classOf[JUnitRunner])
class WrappedGlueContextTest extends FunSuite with 

org.scalatest.mockito.MockitoSugar with BeforeAndAfter  {

  var mockGlueContext : GlueContext = _
  var wrappedGlueContext: WrappedGlueContext = _

  before {
    mockGlueContext = mock[GlueContext]
    wrappedGlueContext = new WrappedGlueContext(mockGlueContext)
  }


 test("Test get dataFrame from glue data catalog source") {

    val mockedDataSource: DataSource= mock[DataSource]
    val mockDynamicFrame: DynamicFrame = mock[DynamicFrame]
    val mockDataFrame: DataFrame = mock[DataFrame]
    assert(wrappedGlueContext.glueContext === mockGlueContext)

    when(mockGlueContext.getCatalogSource(anyString, anyString, anyString)).thenReturn(mockedDataSource)

 }
}

最后一个 when() 调用抛出以下错误:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 0 matchers expected, 3 recorded: This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String"); When using matchers, all arguments have to be provided by matchers. For example: //correct: someMethod(anyObject(), eq("String by matcher")); For more info see javadoc for Matchers class.

getCatalogSource() 的定义如下所示

 def getCatalogSource(database: String, tableName: String, redshiftTmpDir: String = "",
                   transformationContext: String = "", pushDownPredicate: String = "",
                   additionalOptions: JsonOptions = JsonOptions.empty, catalogId: String = null): DataSource = {

为什么我在模拟对象上调用方法 getCatalogSource() 时显示 0 matchers expected

问题是 getCatalogSource() 有我没有使用我的匹配器传递的默认参数。我将测试中的方法调用更改为

 when(mockGlueContext.getCatalogSource(anyString, anyString, anyString, anyString, anyString, any(), any())).thenReturn(mockedDataSource)

测试通过。

如果您使用 mockito 的 scala 版本,将为您处理默认参数,它还允许您混合使用原始参数和参数匹配器