Mock final class in Spock

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

Can spock mock final classes? If so, how? Search results brought up this gist, which would seem to imply so, but I can't find any examples of doing so. I've also found forum posts that say mocking final classes isn't supported.

回答1:

This specification:

@Grab('org.spockframework:spock-core:1.0-groovy-2.4') @Grab('cglib:cglib-nodep:3.1')  import spock.lang.*  class Test extends Specification {     def 'lol'() {         given:          def s = Mock(String) {             size() >> 10         }          expect:         s.size() == 10             } } 

ends with the following exception:

JUnit 4 Runner, Tests: 1, Failures: 1, Time: 29 Test Failure: lol(Test) org.spockframework.mock.CannotCreateMockException: Cannot create mock for class java.lang.String because Java mocks cannot mock final classes. If the code under test is written in Groovy, use Groovy mock. 

The solution is to use GroovyMock:

@Grab('org.spockframework:spock-core:1.0-groovy-2.4') @Grab('cglib:cglib-nodep:3.1')  import spock.lang.*  class Test extends Specification {     def 'lol'() {         given:          def s = GroovyMock(String) {             size() >> 10         }          expect:         s.size() == 10             } } 

Which works well.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!