我有一个使用其他服务的服务,例如:
class ServiceA implements IFaceClass {
ServiceB bServ
@Override
void functionA(Map map) {
try {
bServ.functionB() // this throws an exception on error
} catch (Exception e) {
log.warn("Exception occured: " + e.message)
}
}
}
现在,我正在尝试编写一个单元测试,通过使用以下Spec对该函数进行模拟,以检查
bServ.functionB()
引发了异常并由functionA()
处理了该异常。class ServiceASpec extends Specification {
ServiceB bServ
def setup() {
bServ = Mock(ServiceB)
service.bServ = bServ
}
def "test exception raised by functionB is handled"() {
given:
bServ.functionB() >> {
throw new Exception("some exception message")
}
when:
service.functionA()
then:
1 * log.warn("Exception occured: some exception message")
}
}
但是,此测试说出log.warn语句(0次调用)时出现错误。
感谢您对为何此测试不正确以及如何测试
functionA()
是否正确处理异常的任何见解
最佳答案
在这里您可以找到示例工作测试:
@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')
@Grab('org.slf4j:slf4j-api:1.7.12')
import spock.lang.*
import org.slf4j.Logger
class ServiceASpec extends Specification {
def "test exception raised by functionB is handled"() {
given:
ServiceB serviceB = GroovyMock()
serviceB.functionB() >> { throw new Exception("some exception message") }
and:
ServiceA serviceA = new ServiceA()
serviceA.serviceB = serviceB
serviceA.log = Mock(Logger)
when:
serviceA.functionA([:])
then:
1 * serviceA.log.warn("Exception occured: some exception message")
}
}
class ServiceA {
ServiceB serviceB
Logger log
void functionA(Map map) {
try {
serviceB.functionB()
} catch (Exception e) {
log.warn("Exception occured: " + e.message)
}
}
}
class ServiceB {
void functionB() {
}
}
关于grails - 依赖服务中的Grails单元测试模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856131/