gpt4 book ai didi

java - 在 Spock 框架中模拟

转载 作者:行者123 更新时间:2023-11-28 20:34:40 25 4
gpt4 key购买 nike

我尝试用 Spock 编写测试,但遇到了一些问题。代码会告诉更多...我的测试看起来像:

class MyServiceSpec extends Specification {
private MyService myService
private MyDAO myDAO

def setup() {
myDAO = Mock(MyDAO)
myService = new MyServiceImpl(myDAO)
}

def "Should get something"() {
given:
def user = Mock(User)
def date = now()
myDAO.getUsersSomethingFromDate(_ as User, _ as LocalDate) >> [ Mock(Something) ]

when:
myService.getUsersSomethingFromDate(user, date)

then:
1 * myDAO.getUsersSomethingFromDate(_ as User, _ as LocalDate)
}
}

MyDAO 是一个接口(interface)

我还尝试了不同的 setup 方法:

    def setup() {
myDAO = Mock(MyDAO) {
getUsersSomethingFromDate(_ as User, _ as LocalDate) >> [ Mock(Something) ]
}
myService = new MyServiceImpl(myDAO)
}

尽管我声明方法 getUsersSomethingFromDate 应该返回 [ Mock(Something) ],但它返回 null。在接下来的服务方法运行中,我收到了 NullPointerException,因为返回的是“null”而不是模拟实例列表。问题是为什么具有要返回的声明值的模拟对象仍然返回 null

最佳答案

mock 与调用计数检查的结合存在问题,因为 mock 没有被调用。

您可以用这种方式重写组合测试以使其正常工作:

def "Should get something"() {
given:
def user = Mock(User)
def date = now()

when:
myService.getUsersSomethingFromDate(user, date)

then:
1 * myDAO.getUsersSomethingFromDate(_ as User, _ as LocalDate) >> [ Mock(Something) ]
}

参见 http://spockframework.org/spock/docs/1.3/all_in_one.html#_combining_mocking_and_stubbing

关于java - 在 Spock 框架中模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com