首页 > 解决方案 > 在 Groovy 中存根时出现 InvalidUseOfMatchersException

问题描述

我有一个这样的 Java 方法签名:

public Resource generatePDF(
  List<InvoiceReportEntity> invoices,
  String labelerCd,
  InvoiceContactEntity contact,
  CalculatedInvoiceAmount calculatedInvoice,
  InvoicePaymentEntity invoicePaymentsAddress,
  List <InvoiceReportPpaEntity> allQuartersInvoicePpaList,
  BigDecimal currQtrInterestAmt,
  List<InvoicePpaInterest> intAmt,
  Integer invoiceYearQtr
)

这是我用 Groovy 编写的单元测试:

def '10.Export PDF with valid id'() {
    given:'Valid id'
    def invoiceIds = ['AL4-00008-20192']
    def types = [ExportType.PDF] as ExportType[]

    and:
    def mockInvoicePDFProcessor = mock(InvoicePDFProcessor)

    when(
      mockInvoicePDFProcessor.generatePDF(
        any(List.class),
        anyString(),
        any(InvoiceContactEntity.class),
        any(CalculatedInvoiceAmount.class),
        any(InvoicePaymentEntity.class),
        any(List.class),
        any(BigDecimal.class),
        any(List.class),
        any(Integer.class)
      )
    )
    .thenReturn(mock(Resource));
    invoiceController.setPdfProcessor(mockInvoicePDFProcessor)

    when: 'Retrieve results based on invoice header id'
    def response = invoiceController.exportInvoiceData(
      types, invoiceIds,
      mock(HttpServletResponse)
    )

    then: 'response received'
    response.getStatusCode().value() == 200
    response.hasBody()
}

该测试在单独运行时通过,但是当整个测试用例运行时,我得到了这个异常

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:
-> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
-> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
-> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
-> at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallStatic(CallSiteArray.java:56)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
    at 10.Export PDF with valid id(InvoiceControllerSpec.groovy:222)**

我已经将 .class 用于上面使用的所有类,结果仍然相同。我已经搜索过类似的错误,但不幸的是这里提到的解决方案对我不起作用:

标签: javagroovyspock

解决方案


推荐阅读