java - Spock stub 在功能方法中不起作用

标签 java unit-testing spock

我正在使用 spock 编写单元测试。在创建测试用例时,我正在模拟对象并使用响应来 stub 函数调用。但是,当在主题类/服务类中执行 stub 调用时, stub 方法将返回 null 而不是实际值。如果我尝试访问测试类中的 stub 值,我可以访问它,但在 stub 类中,它为我的 stub 返回 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,这是我声明 stub 错误的地方吗?因为如果我在 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;
    }

    ...
}

关于java - Spock stub 在功能方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55914920/

相关文章:

java - 在启动时引导 Java 应用程序 - Raspberry Pi - Raspbian - Shell 脚本

java - Spock 模拟验证返回 0 次调用

.net - 如何减少 .NET 中的 MSTest 执行时间?

mockito - 在基于 spock 的测试中对 mockito 模拟对象进行 stub

grails 2.5.1 忽略了 Spock 功能测试

java - Grooveshark api 总是返回 "Method not found"消息

java - autonicrement berkeley db,或列表

java - 以表格形式显示

javascript - 如何使用 jest 在一定时间的模拟时间后运行断言测试?

testing - _(下划线)在 Spock 测试中意味着什么?