gpt4 book ai didi

spring - Spock 如何在方法中模拟 Autowired 类的函数调用

转载 作者:行者123 更新时间:2023-12-03 20:18:31 24 4
gpt4 key购买 nike

我有一个要测试的类,如下所示:
包com.something;

import org.springframework.beans.factory.annotation.Autowired;
public class ClassToTest implements InterfaceToTest{

@Autowired
AnotherService serviceA;

@Override
public List<String> methodToTest(List<String> randomVar){
...
String stringA = serviceA.someFunction(randomVar);
...
}
}

在使用 spock 进行测试时,如何模拟调用 serviceA.someFunction(randomVar) 的结果以返回我选择的任何字符串?
package com.something;
import spock.lang.Shared
import spock.lang.Specification
class TestClass extends Specification{
@Shared InterfaceToTest classToTest = new ClassToTest()

static doWithSpring = {
serviceA(AnotherService)
}

def "tests-part-1"(){
when: "something"
...
then: "expect this"
...
}
}

我不知道从这里去哪里。我的 IDE 显示了我添加到测试类中的 doWithSpring 代码的错误。关于如何处理这个问题的任何想法?

最佳答案

我建议从更多的单元测试角度考虑它。你想模拟 spring 框架的东西,并确保你正在测试你的逻辑。 Spock 很容易做到这一点。

ClassToTest myClass = new ClassToTest(serviceA: Mock(AnotherService))

def "test my method"() {
when:
myClass.methodToTest([])

then:
1 * myClass.serviceA.someFunction([]) >> 'A string'
}

从这里,您可以查看驱动它的数据或使用 >>> 并传递您想要返回的不同字符串的列表。

关于spring - Spock 如何在方法中模拟 Autowired 类的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38878338/

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