Вопрос

I test Java code with Spock. I test this code:

 try {
    Set<String> availableActions = getSthAction()
    List<String> goodActions = getGoodAction()
    if (!CollectionUtils.containsAny(availableActions ,goodActions )){
       throw new CustomException();
    }
} catch (AnotherCustomExceptio e) {
     throw new CustomException(e.getMessage());
}

I wrote test:

def "some test"() {
    given:
    bean.methodName(_) >> {throw new AnotherCustomExceptio ("Sth wrong")}
    def order = new Order();
    when:
    validator.validate(order )
    then:
    final CustomException exception = thrown()
}

And it fails because AnotherCustomExceptio is thrown. But in the try{}catch block I catch this exception and throw a CustomException so I expected that my method will throw CustomException and not AnotherCustomExceptio. How do I test it?

Это было полезно?

Решение

I believe your then block needs to be fixed. Try the following syntax:

then:
thrown CustomException

Другие советы

If you would like to evaluate for instance the message on the thrown Exception, you could do something like:

then:
def e = thrown(CustomException)
e.message == "Some Message"

There could be multiple ways to handle the exception in then:

thrown(CustomException)

or

thrown CustomException

As well we can check if no Exception is thrown in the Test case -

then:

noExceptionThrown()
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top