Spock & Spock Reports: how "catch" and customize the error message for AssertionError?

1.4k Views Asked by At

I am working with:

  • Spock Core
  • Spock Reports
  • Spock Spring
  • Spring MVC Testing

and I have the following code:

@FailsWith(java.lang.AssertionError.class)
def "findAll() Not Expected"(){

    given:

        url =  PersonaUrlHelper.FINDALL;

    when: 

        resultActions = mockMvc.perform(get(url)).andDo(print())

    then: 

        resultActions.andExpect(status().isOk())
                     .andExpect(content().contentType(MediaType.APPLICATION_XML))


}

Here the code fails (how is expected) because the method being tested really returns (MediaType.APPLICATION_JSON) instead of (MediaType.APPLICATION_XML).

So that the reason of @FailsWith(java.lang.AssertionError.class).

Even if I use @FailsWith(value=java.lang.AssertionError.class, reason="JSON returned ...") I am not able to see the reason through Spock Reports

Question One: how I can see the reason on Spock Reports?.

I know Spock offers the thrown() method, therefore I am able to do:

  then:
        def e = thrown(IllegalArgumentException)
        e.message == "Some expected error message"
        println e.message

Sadly thrown does not work for AssertionError.

If I use thrown(AssertionError) the test method does not pass, unique way is through @FailsWith but I am not able to get the error message from AssertionError

Question Two how is possible get the Error Message from AssertionError?

I know I am able to do something like

then: "Something to show on Spock Reports"

But just curious if the question two can be resolved..

1

There are 1 best solutions below

0
On

regarding Question one:

if you look at FailsWithExtension#visitFeatureAnnotation you can see that only value from the @FailsWith is evaluated, reason is not touched at all. What you could do is introduce you own type of annotation (custom one, e.g. same as @FailsWith) and override AbstractAnnotationDrivenExtension#visitFeatureAnnotation. There you have access to reason parameter.

regarding Question two:

please look at this link: http://spock-framework.3207229.n2.nabble.com/Validate-exception-message-with-FailsWith-td7573288.html

additionally maybe you could override AbstractAnnotationDrivenExtension#visitSpec and add custom listener (overriding AbstractRunListener). Then you have access to AbstractRunListener#error method whose documentation says:

Called for every error that occurs during a spec run. May be called multiple times for the same method, for example if both * the expect-block and the cleanup-block of a feature method fail.

Didn't test for Question two, but it may work. I've used sth similar.

Enjoy,

Tommy