Spock存根在功能方法中不起作用



我正在使用SPOCK编写单元测试。在创建测试用例时,我正在嘲笑对象,并用响应将函数调用固定。但是,当在主题类/服务类中执行固定呼叫时,固执方法将返回null而不是实际值。如果我尝试访问测试类中的固执值,我可以访问它,但是在固执的类中,它正在返回null。

下面是我执行的样本

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

预期的响应是" test ",但是它正在返回null,这是我声明Stubs错误的地方吗?因为如果我在setupspec((方法中声明此内容,则一切都按预期工作。

您应该以某种方式将模拟的CacheService传递到ServiceClass中。

测试的可能变体之一是:

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

ServiceClass具有通过缓存服务的相应构造函数:

class ServiceClass {
    private final CacheService cacheService;
    ServiceClass(CacheService cacheService) {
       this.cacheService = cacheService;
    }
    ...
}

最新更新