4.5. Summary

  • Spock contains several blocks/labels to mark the phases inside a unit test. They help readability of the test and in some cases enforce the code structure. (Spock will reject assignments when an assertion was expected.)
  • The given: block creates the scene for the test, the when: block triggers the tested action, and the then: block examines the result. The given-then-when structure is the suggested structure for Spock tests.
  • The and: block can be used on any other block as a semantic extension.
  • The expect: block is a combination of then: and when: and can be used for trivial tests or as an intermediate precondition in longer tests.
  • The cleanup: block will always run at the end of a Spock test regardless of the test result. It’s used to release resources.
  • Spock test methods can have full sentences as names. You should always exploit this feature to better describe what your method does.
  • The @Subject annotation should be used to mark the class under test. You can use it individually in each test method, or at the class level if all test methods focus on a single class.
  • The @Title annotation should be used to explain with full English text what your Spock test does.
  • The @Narrative annotation can be used for a longer description of a Spock test.
  • Spock methods setup() and cleanup() run before and after each test method. They run as many times as test methods exist.
  • Spock methods setupSpec() and cleanupSpec() run once before all test methods and once after they’re finished.
  • Spock supports and understands JUnit annotations such as @Before, @After, @BeforeClass, and @AfterClass.
  • The @Shared annotation marks long-lived objects that span all test methods. The setupSpec() and cleanupSpec() methods work only with objects that are either static or marked with the @Shared annotation.
  • The old() method can be used in specific cases to capture the relative change of the class state instead of comparing absolute values before and after the triggered action.
  • A Spock test can have multiple then: blocks, which are executed in the order they’re mentioned.
  • All Spock blocks should have an English description next to them for readability.
  • Spock calls the Java toString() method automatically on any involved class when a test fails. Overriding this method allows you to define what will be shown on failed tests.
  • Spock natively supports Hamcrest matchers with three alternative syntax variations.
  • Spock natively supports JUnit rules out of the box.
  • The Groovy object.with construct can be used to group object parameterization inside Spock tests.
  • The Spock Specification.with construct can be used to group assertions to a single object.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.129.194