简体   繁体   中英

Spock stub not working in the feature method

I'm writing a unit test using spock. While creating the test case, I'm mocking the objects and stubbing the function calls with a response. But when the stubbed calls are executed in the subject class /service class, the stubbed methods are returning null instead of actual value. If i try to access the stubbed value in the test class, I'm able to access it but in stubbed class it is returning null for my stubbing.

Below is sample I'm executing

class Test extends Specification{
    def ServiceClass = new ServiceClass()
    def "test doSomething method"(){
        given:
        String id = "id"
        def cacheService = Mock(CacheService)
        def obj = Mock(CacheObj)
        cacheService.get(_) >> obj
        obj.getValue("thisID") >> "test"  //stubbing this to return test
        when:
        //calling dosomething() method of service class
        cacheService.doSomething(id)
        then:
        //checking assertions here
    }
}


class ServiceClass{
    public String doSomething(String id){
        Object obj = cacheService.get(id);
        String val = obj.getValue("thisID") // while executing this, val is returning **null**, but it should ideally return "test" as it is stubbed in specification class
    }
}

The expected response is " test ", but it is returning null, is it the place where i'm declaring stubs wrong? Because if I declare this in setupSpec() method, everything works as expected.

You should pass somehow the mocked CacheService into ServiceClass .

One of possible variants of the test is:

class ServiceClassTest extends Specification {
    def "doSomething(String) should return a value of cached object"() {
        given: "some id"
        def id = "id"

        and: "mocked cached object which returns 'test' value"
        def obj = Mock(CacheObj)
        obj.getValue("thisID") >> "test"

        and: "mocked cached service which returns the cached object by given id"
        def cacheService = Mock(CacheService)
        cacheService.get(id) >> obj

        and: "a main service with injected the mocked cache service"
        def serviceClass = new ServiceClass(cacheService)

        expect:
        serviceClass.doSomething(id) == "test
    }
}

The ServiceClass has the corresponding constructor to pass a cache service:

class ServiceClass {
    private final CacheService cacheService;

    ServiceClass(CacheService cacheService) {
       this.cacheService = cacheService;
    }

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM