【发布时间】:2019-09-18 18:15:00
【问题描述】:
我正在使用 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,这是我声明存根错误的地方吗?因为如果我在 setupSpec() 方法中声明它,一切都会按预期工作。
【问题讨论】:
-
如何将 mock 放入您的 ServiceClass?请修复代码以便编译。见MCVE
-
我同意伦纳德的要求。其他问题是:您想如何在
Object类型上调用getValue()?CacheService类在哪里?还请完成测试,不要用 cmets 替换代码。这样没人能帮你。
标签: java unit-testing spock