本文介绍了在Spock中模拟最后一堂课的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spock可以模拟最后的课程吗?如果是这样,怎么办?搜索结果显示了这个要点,这似乎暗示了这一点,但是我找不到这样做的任何例子.我还发现论坛上的帖子说不支持模拟最终课程.

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.

推荐答案

此规范:

@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        
    }
}

以以下例外结尾:

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.

解决方案是使用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        
    }
}

哪个效果很好.

这篇关于在Spock中模拟最后一堂课的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 18:30