问题
I am new to Groovy and trying to implement Spock framework in my application. Here is my test code:
def "Test class with mock object"() {
setup:
SomeObject sp = Mock()
test= TestClass()
when:
System.out.println('comes here');
push.exec(sp)
then:
sp.length == 1
}
Here TestClass
is throwing some exception which I have to catch in test method or throw it again. I tried
try {
push.exec(sp)
} catch (Exception e) {
}
But still getting
groovy.lang.MissingMethodException: No signature of method: test.spock.TestClassTest.TestClass() is applicable for argument types: () values: []
Possible solutions: use([Ljava.lang.Object;), use(java.util.List, groovy.lang.Closure), use(java.lang.Class, groovy.lang.Closure), dump(), with(groovy.lang.Closure), each(groovy.lang.Closure)
回答1:
Instead of test = TestClass()
, it should be test = new TestClass()
. To test for an expected exception, use Specification.thrown
instead of try-catch. See Spock's Javadoc for an example.
回答2:
That's the correct way to handle exceptions in Spock:
def "Test class with mock object"() {
setup:
SomeObject sp = Mock()
test= TestClass()
when:
System.out.println('comes here');
push.exec(sp)
then:
thrown(YourExceptionClass)
sp.length == 1
}
or if you want to check some data in your exception you may use something like:
then:
YourExceptionClass e = thrown()
e.cause == null
来源:https://stackoverflow.com/questions/15909716/throw-catch-exception-in-groovy