Spock 配置

技巧

Mock 静态方法

GroovyMock 也可以 mock 静态方法,但其只能 mock 由 Groovy 编写的静态方法,不能对 Java 编写的静态方法进行 mock,需要使用其他方法进行 mock。

spock-1.x 版本中 mock 静态方法使用 powermock,而在 2.x 中需要使用 Mockito-3.4[1]

mockito 需要依赖以下 jar:

org.mockito:mockito-core:4.3.1
org.mockito:mockito-inline:4.3.1

使用方法:

class StudentTest extends Specification {

    Mockito.mockStatic(IDGenerator.class)

    def "should success when create student"() {
        given:
            var name = "tester"
            var code = "123456"
            Mockito.when(IDGenerator.nextId()).thenReturn("123456789")
        when:
            var student = Student.create(name, code)
        then:
           student.getId() == "123456789"
    }
}

class StudentTest extends Specification {

    MockedStatic generator

    def setup() {
        generator = Mockit.mockStatic(IDGenerator.class)
    }

    // The test case 
    def cleanup() {
        // eliminate Mock Static method of 
        generator.close()
    }
}

Maven 工程

pom.xml 依赖以下内容:


  2.1-groovy-3.0
  1.12.9
  4.3.1
  1.2.11



  
    
      org.spockframework
      spock-bom
      ${spock.version}
      pom
      import
    
  



  
  
    org.spockframework
    spock-core
    test
  

  
    net.bytebuddy
    byte-buddy
    ${byte-buddy.version}
    test
  

  
    org.mockito
    mockito-core
    ${mockito.version}
    test
  

  
    org.mockito
    mockito-inline
    ${mockito.version}
    test
  

  
    ch.qos.logback
    logback-classic
    ${logback.version}
    test
  




    maven-surefire-plugin
    3.0.0-M5



  org.codehaus.gmavenplus
  gmavenplus-plugin
  1.13.1
  
    
      
        compile
        compileTests
      
    
  
  
    
      
        ${project.basedir}/src/test/groovy
        
          **/*.groovy
        
      
    
  


  1. https://copyfuture.com/blogs-details/202205082152513359 ↩

你可能感兴趣的:(Spock 配置)