Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock final class in 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.

like image 991
Julian A. Avatar asked Dec 06 '15 20:12

Julian A.


People also ask

Can we mock final class with Mockito?

Before we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

How do you mock a method in Spock?

In Spock, a Mock may behave the same as a Stub. So we can say to mocked objects that, for a given method call, it should return the given data. So generally, this line says: itemProvider. getItems will be called once with ['item-'id'] argument and return given array.

Does Spock use JUnit?

Both Groovy and Java build and run on the JVM. A large enterprise build can run both JUnit and Spock tests in the same time. Spock uses the JUnit runner infrastructure and therefore is compatible with all existing Java infrastructure. For example, code coverage with Spock is possible in the same way as JUnit.


1 Answers

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.

like image 174
Opal Avatar answered Sep 17 '22 00:09

Opal