Search code examples
kotlingroovymockitospockpowermockito

How to access Kotlin static method in Groovy Spock test


I have kotlin class below

class DPCIValidator {

companion object {
     fun validate(value: String): Boolean {
        val regex = Regex(pattern = "\\d\\d\\d-\\d\\d-\\d\\d\\d\\d")
        return regex.matches(value)
     }
  }
}

Spock test below, I am unable to access Kotlin static method via spock

testImplementation 'org.spockframework:spock-spring:2.2-M1-groovy-3.0'
import spock.lang.Specification

class DPCIValidatorSpec extends Specification{

def 'test static method validate'(){
    when:
    Boolean test = DPCIValidator.validateDPCI("001-02-1234")

    then:
    assert test == true
}

Any help appreciated

Edit: updated spock test


Solution

  • You have to add the @JvmStatic on your companion method.

    See the following code :

    class DPCIValidator {
    
    companion object {
        @JvmStatic
        fun validate(value: String): Boolean {
            val regex = Regex(pattern = "\\d\\d\\d-\\d\\d-\\d\\d\\d\\d")
            return regex.matches(value)
        }
    }
    

    }

    It specifies that a static method needs to be generated.

    For more information see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-static/