无效使用参数匹配器0个匹配项。 3记录

时间:2018-11-09 23:05:54

标签: scala unit-testing mockito aws-glue

我正在使用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 = {

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

2 个答案:

答案 0 :(得分:2)

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

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

测试通过。

答案 1 :(得分:0)

如果您使用的是mockito的Scala版本,则将为您处理默认参数,这也将允许您混合使用原始参数和参数匹配器