gpt4 book ai didi

unit-testing - 如何模拟一种在clazz中传递的方法?

转载 作者:行者123 更新时间:2023-12-02 16:00:48 25 4
gpt4 key购买 nike

我正在尝试为具有.class参数的方法编写单元测试。

例如:

ExampleService {
def myExample(clazz){
//do stuff and return some object
}
}

/* How the above function gets used */
AnotherExampleService extends exampleService {


def blah() {
def obj = myExample(AnotherClass.class)
}
}

/* Now I need to test the above blah() function */
AnotherExampleServiceSpec extends Specification {
def "test blah"() {
//The following doesn't seem to work
ExampleService.metaClass.myExample = { def arg1 -> obj }
}
}

我对Groovy / Grails来说还很陌生,所以任何帮助将不胜感激。我基本上想知道为什么我的单元测试似乎不起作用,以及如何测试带有类实例参数的函数。
谢谢您的帮助!

最佳答案

我可能会在测试中将ExampleService子类化。所以它看起来像:

ExampleService {
def myExample(clazz){
//do stuff and return some object
}
}

AnotherExampleService extends ExampleService {
def exampleService

def blah() {
def obj = myExample(AnotherClass)
}
}

AnotherExampleServiceSpec extends Specification {
def "test blah"() {
given:
AnotherExampleService service = new AnotherExampleService() {
@Override
def myExample(clazz){
//whatever you want to do
return whatEverResult
}
when:
def result = service.blah (SomeClass)
then:
result
}
}

如您所见,这里重写了myExample方法以返回一些模拟值,并且无需修改元类:-)为了使Groovy更容易,您可以显式声明输入类型,例如 def myExample(Class clazz)

关于unit-testing - 如何模拟一种在clazz中传递的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31330632/

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