SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
2
INTRODUCTION TO
Sp●ck
NAIYER ASIF
1
What’s Sp●ck?
Spock is a high-level testing framework
written in Groovy
by Peter Niederwieser
in 2008
Spock is also
 open-source https://github.com/spockframework/spock
 enterprise-ready (used by Netflix, Apache Tapestry and Spring)
Spock supports
 Java, Groovy, Scala, Kotlin and even JavaScript
 Maven, Gradle and Grape (with experimental support for SBT and Bazel)
WHAT’S SP●CK?
2
Spock can handle the entire lifecycle of an application.
It can be used to
 unit test classes
 mock and stub the objects
 test the behavior of a story
3
Features of Sp●ck
 A highly expressive Business Readable DSL
 Fully compatible with JUnit Test Runner
− Runs on Sputnik Test Runner which in turn uses JUnit Test Runner
 Meticulous and relevant diagnostics
 Inbuilt Mocking framework
 Agnostic Tests
 Extends through modules for
− Spring
− Android
− Tapestry
− Guice
− Genesis
− Reports, and more…
Tests written in Java,
Groovy, etc
Tests written in
JavaScript
Sputnik
Test
Runner
Test Results
4
Running Sp●ck with Gradle
Configure build.gradle as follows –
apply plugin: "groovy"
repositories {
jcenter()
}
dependencies {
testCompile "org.spockframework:spock-core:1.1-groovy-2.4-rc-2"
}
A custom version of groovy can also be used. Just include it as a dependency –
compile "org.codehaus.groovy:groovy-all:2.4.12"
5
Running Sp●ck with Maven
Add the following dependency in pom.xml –
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.1-groovy-2.4-rc-2</version>
<scope>test</scope>
</dependency>
Spock comes with its own version of groovy. A custom version of groovy can also be used –
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.12</version>
</dependency>
RUNNING SP●CK WITH MAVEN
6
To run Spock tests using mvn test, add the following plugins –
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<useFile>false</useFile>
<includes>
<include>**/*Spec.java</include>
<include>**/*Spec.groovy</include>
</includes>
</configuration>
</plugin>
7
Sp●ck Specifications
import spock.lang.Specification
class FirstSpec extends Specification {
def "length of Carmaker name"() {
expect:
"BMW".length() == 3
}
}
 Spock tests are written in groovy.
 Semicolons are optional.
 Method names follow def keyword and can be string.
 Every Spock test class is called a Specification because it extends spock.lang.Specification class. By convention, they end with
Spec.
 A test method in a Specification is called a feature method, which in turn is equivalent to a JUnit test.
 Feature methods are public.
8
Block Taxonomy
Block Use
given: Used for creating objects, setting up data, launching web pages, logging in before testing access controlled
functionality, etc.
setup: an alias of given:
when: Controls the behavior being tested like initiating an action by a mocked object, interacting with an element on a
webpage, etc.
A when: block must be followed by a then: block.
then: Makes assertions about the results of when: block. Requires a preceding when: block
expect: Makes assertions without requiring when: block. Can be used to check the initial states of objects or preconditions of
when: block.
cleanup: Allows a safe tear-down of resources. Analogous to finally block in Java.
where: Used for parametrized feature methods and listing data tables
and: Used to extend a preceding block. Useful to break a huge expect: or when: block into smaller readable blocks
9
Sp●ck Specifications: A Taste of DSL
Consider the following JIRA story –
Create a utility to sum the digits of an integer to unit
Acceptance Criteria
Given When Then
Number = 1234
Digits are summed
Result = 1
Number = 15678 Result = 9
Number = -35567 Result = 8
Number = 0 Result = 0
SP●CK SPECIFICATIONS: A TASTE OF DSL
10
The Spock specification for the aforementioned story can be written as –
import spock.lang.Specification
class UnitSumTest extends Specification {
def "Test summation to a unit" () {
given:
def sum = new UnitSum()
expect:
sum.getUnitSum(input) == output
where:
input | output
1234 | 1
15678 | 9
-35567 | 8
0 | 0
}
}
Note the relative similarity between story and test, both describing the same behavior.
11
Sp●ck Specifications: Grouped Assertions
Consider a Java class –
public class User {
...attributes
public User(String username) {
this.username = username;
this.following = new ArrayList<>();
this.posts = new ArrayList<>();
this.registered = Instant.now();
}
...getters and setters
}
SP●CK SPECIFICATIONS: GROUPED ASSERTIONS
12
Instead of asserting for individual properties one by one, the assertions can be grouped as follows, using Spock’s with method –
import spock.lang.Specification
import java.time.Instant
class GroupedAssertionsSpec extends Specification {
def "Multiple Assertions on an Object"() {
given:
def user = new User("Emma")
expect:
with(user) {
username == "Emma"
following.isEmpty()
posts.isEmpty()
registered instanceof Instant
}
}
}
13
Sp●ck Specifications: Expecting Exceptions
import spock.lang.Specification
class ExpectExceptionSpec extends Specification {
def "Expect StringIndexOutOfBoundsException"() {
setup:
def str = "Grace is Eternal"
when:
str.getAt(43)
then:
thrown(StringIndexOutOfBoundsException)
}
}
 thrown method will pass only if exception is thrown in when: block
14
Sp●ck Specifications: Interrogating Exceptions
import spock.lang.Specification
class InterrogateExceptionSpec extends Specification {
def "Interrogate ArithmeticException"() {
given:
def num = 10
def zero = 0
when:
num / zero
then:
def e = thrown(ArithmeticException)
e.message == "Division by zero"
}
}
 This test passes iff ArithmeticException is thrown and the message matches.
15
Sp●ck Specifications: Unrolling
import spock.lang.Specification
class UnrollingSpec extends Specification {
def "Test for Palindrome" () {
given:
def palindrome = new SimplePalindrome()
expect:
palindrome.isPalindrome(str) == expected
where:
str | expected
"BOB" | true
"vIv" | true
"A" | true
"Holly" | false
}
}
• Without unrolling the entire specification runs without informing precisely which iterations failed or passed
• A series of exceptions are thrown and developer has to figure out which exception corresponds to which test failure
SP●CK SPECIFICATIONS: UNROLLING
16
The same specification with unrolling enabled –
import spock.lang.Specification
import spock.lang.Unroll
class UnrollingSpec extends Specification {
@Unroll("is #str a palindrome? #answer")
def "Test for Palindrome" () {
given:
def palindrome = new SimplePalindrome()
expect:
palindrome.isPalindrome(str) == expected
where:
str | expected
"BOB" | true
"vIv" | true
"A" | true
"Holly" | false
answer = expected ? "YES" : "NO"
}
}
17
Specification Lifecycle: Fixture Methods
Name When run Similar to JUnit
setup() Before each test @Before
cleanup() After each test @After
setupSpec() Before first test @BeforeClass
cleanupSpec() After last test @AfterClass
The lifeline of various methods in a Specification –
1. setupSpec()
2. setup()
3. feature method 1()
4. cleanup()
5. setup()
6. feature method 2()
7. cleanup()
8. ...
9. cleanupSpec()
18
Resource Sharing
import spock.lang.Shared
import spock.lang.Specification
class ArrayListSpec extends Specification {
@Shared list = new ArrayList<String>()
def "check if list is clear"() {
list.add("Allspark")
when:
list.clear()
then:
list.size() == 0
}
}
 Resources that are needed in several features can be declared as @Shared
19
Resource Management
import spock.lang.Shared
import spock.lang.Specification
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.Statement
class DatabaseSpec extends Specification {
private final url = "jdbc:mariadb://localhost:3306/spring"
private final username = "erin"
private final password = "richards"
@Shared Connection connection
def setup() {
connection = DriverManager.getConnection(url, username, password)
}
RESOURCE MANAGEMENT
20
def "DB test"() {
given:
Statement statement = connection.createStatement()
final query = "select * from book where book_id = 1"
when:
ResultSet resultSet = statement.executeQuery(query)
then:
resultSet.getMetaData().getColumnCount() > 1
cleanup:
resultSet.close()
}
def cleanup() {
connection.close()
}
}
21
Specification Lifecycle: Revisited
Consider two Specifications SuperSpec and SubSpec, where SubSpec is a child of abstract SuperSpec. When SubSpec is tested, the
Spock lifecycle follows the following lifeline –
1. super setupSpec()
2. sub setupSpec()
3. super setup()
4. sub setup()
5. sub feature method 1()
6. sub cleanup()
7. super cleanup()
8. super setup()
9. sub setup()
10. sub feature method 2()
11. sub cleanup()
12. super cleanup()
13. ...
14. sub cleanupSpec()
15. super cleanupSpec()
 Execution of the setupSpec and setup methods proceeds down the inheritance tree
 Execution of the cleanupSpec and cleanup methods proceeds up the inheritance tree
22
Specification Inheritance
import spock.lang.*
import java.sql.*
abstract class DatabaseSpec extends Specification {
private final url = "jdbc:mariadb://localhost:3306/spring"
private final username = "erin"
private final password = "richards"
@Shared Connection connection
def setup() {
connection = DriverManager.getConnection(url, username, password)
}
def cleanup() {
connection.close()
}
}
SPECIFICATION INHERITANCE
23
import java.sql.ResultSet
import java.sql.Statement
class BookQuerySpec extends DatabaseSpec {
private static ResultSet resultSet
def "DB test"() {
given:
Statement statement = connection.createStatement()
final query = "select * from book where book_id = 1"
when:
resultSet = statement.executeQuery(query)
then:
resultSet.getMetaData().getColumnCount() > 1
}
def cleanup() {
resultSet.close()
}
}
24
Conditional Testing
Annotations for conditional testing of Specifications/feature methods –
@Ignore Forces the test runner to skip a particular feature method or specification
class
@IgnoreRest Isolates a single feature method or specification class that should be
executed while the rest of the suite is skipped
@PendingFeature A variant of @Ignore.
Feature methods annotated with @PendingFeature are executed with
the expectation that they will fail. If a feature method annotated with
@PendingFeature actually passes, that is reported as an error.
25
Sp●ck Diagnostics
import spock.lang.Specification
class DiagnosticsSpec extends Specification {
def "check string length"() {
given:
def str = new StringBuilder()
expect:
str.append("Hello").append("-World").replaceAll("-", ", ").toString() == "Hello World"
}
}
 given describes the pre-condition
 expect is the assertion
SP●CK DIAGNOSTICS
26
When DiagnosticsSpec is run, the following message is displayed –
Condition not satisfied:
str.append("Hello").append("-World").replaceAll("-", ", ").toString() == "Hello World"
| | | | | |
| Hello-World Hello-World Hello, World | false
Hello-World | 1 difference (91% similarity)
| Hello(,) World
| Hello(-) World
Hello, World
Expected :Hello World
Actual :Hello, World
<Click to see difference>
at in.naiyer.spock.basic.DiagnosticsSpec.check string length(DiagnosticsSpec.groovy:12)
 The values are evaluated at the end of every expression.
 The most relevant line of stacktrace is printed.
 A diff window is available to compare the expected and actual values.
27
Get the Code
https://bitbucket.org/microflash/spock-intro
28
What Next?
 @Stepwise Specifications
 Integration Testing
 Functional Testing of REST services
 Testing Reactive applications
 Browser Automation and E2E Testing with Selenium & Geb
 Build Pipelining with Spock
 Code coverage from Spock
 Spock integration with TeamCity and JIRA
 Spock Extensions
 Testing JavaScript, Scala, Kotlin, Groovy, etc. with Spock
29
References
Darwin, Ian: Java Testing for Developers (O’Reilly, 2016)
Fletcher, Rob: Spock: Up and Running (O’Reilly, 2017)
Kapelonis, Konstantinos: Java Testing with Spock (Manning, 2016)
Kapelonis, Konstantinos: Spock: A Logical Framework for Enterprise Testing (GR8Conf US, 2014)
Niederwieser, Peter: Spock Framework Example Project (Github, 2012)
Niederwieser, Peter: Testing Java, Groovy, Spring and Web Applications with Spock (springone, 2014)
Spock Framework Website: http://spockframework.org
30
Contacts
Peter Niederwieser Luke Daley Rob Fletcher Konstantinos Kapelonis
Stack Overflow @ldaley @rfletcherEW @codepipes
http://ldaley.com/ http://codepipes.com/

Mais conteúdo relacionado

Mais procurados

OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQLRoberto Franchini
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestHoward Lewis Ship
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCPEric Jain
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능knight1128
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Andres Almiray
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Andres Almiray
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0Vasil Remeniuk
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 

Mais procurados (19)

OrientDB - The 2nd generation of (multi-model) NoSQL
OrientDB - The 2nd generation of  (multi-model) NoSQLOrientDB - The 2nd generation of  (multi-model) NoSQL
OrientDB - The 2nd generation of (multi-model) NoSQL
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
De Java 8 a Java 17
De Java 8 a Java 17De Java 8 a Java 17
De Java 8 a Java 17
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능Jdk(java) 7 - 6 기타기능
Jdk(java) 7 - 6 기타기능
 
Thread dumps
Thread dumpsThread dumps
Thread dumps
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 

Semelhante a Spock

Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfAppster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfAppster1
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationSergey Arkhipov
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleSkills Matter
 
Dependency injection in scala
Dependency injection in scalaDependency injection in scala
Dependency injection in scalaMichal Bigos
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
Spark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing sparkSpark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing sparkAnu Shetty
 

Semelhante a Spock (20)

Spock
SpockSpock
Spock
 
Agile Swift
Agile SwiftAgile Swift
Agile Swift
 
Gradle
GradleGradle
Gradle
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Kirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for AutomatizationKirill Rozin - Practical Wars for Automatization
Kirill Rozin - Practical Wars for Automatization
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Play framework
Play frameworkPlay framework
Play framework
 
Dependency injection in scala
Dependency injection in scalaDependency injection in scala
Dependency injection in scala
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Spark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing sparkSpark summit2014 techtalk - testing spark
Spark summit2014 techtalk - testing spark
 

Último

Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfQ-Advise
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityamy56318795
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationWave PLM
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersEmilyJiang23
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfmbmh111980
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024vaibhav130304
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfDeskTrack
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfFurqanuddin10
 
The Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionThe Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionWave PLM
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1KnowledgeSeed
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdfkalichargn70th171
 
How to pick right visual testing tool.pdf
How to pick right visual testing tool.pdfHow to pick right visual testing tool.pdf
How to pick right visual testing tool.pdfTestgrid.io
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 

Último (20)

Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
AI Hackathon.pptx
AI                        Hackathon.pptxAI                        Hackathon.pptx
AI Hackathon.pptx
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
The Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionThe Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion Production
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
How to pick right visual testing tool.pdf
How to pick right visual testing tool.pdfHow to pick right visual testing tool.pdf
How to pick right visual testing tool.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 

Spock

  • 2. 1 What’s Sp●ck? Spock is a high-level testing framework written in Groovy by Peter Niederwieser in 2008 Spock is also  open-source https://github.com/spockframework/spock  enterprise-ready (used by Netflix, Apache Tapestry and Spring) Spock supports  Java, Groovy, Scala, Kotlin and even JavaScript  Maven, Gradle and Grape (with experimental support for SBT and Bazel)
  • 3. WHAT’S SP●CK? 2 Spock can handle the entire lifecycle of an application. It can be used to  unit test classes  mock and stub the objects  test the behavior of a story
  • 4. 3 Features of Sp●ck  A highly expressive Business Readable DSL  Fully compatible with JUnit Test Runner − Runs on Sputnik Test Runner which in turn uses JUnit Test Runner  Meticulous and relevant diagnostics  Inbuilt Mocking framework  Agnostic Tests  Extends through modules for − Spring − Android − Tapestry − Guice − Genesis − Reports, and more… Tests written in Java, Groovy, etc Tests written in JavaScript Sputnik Test Runner Test Results
  • 5. 4 Running Sp●ck with Gradle Configure build.gradle as follows – apply plugin: "groovy" repositories { jcenter() } dependencies { testCompile "org.spockframework:spock-core:1.1-groovy-2.4-rc-2" } A custom version of groovy can also be used. Just include it as a dependency – compile "org.codehaus.groovy:groovy-all:2.4.12"
  • 6. 5 Running Sp●ck with Maven Add the following dependency in pom.xml – <dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>1.1-groovy-2.4-rc-2</version> <scope>test</scope> </dependency> Spock comes with its own version of groovy. A custom version of groovy can also be used – <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.12</version> </dependency>
  • 7. RUNNING SP●CK WITH MAVEN 6 To run Spock tests using mvn test, add the following plugins – <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.5</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <useFile>false</useFile> <includes> <include>**/*Spec.java</include> <include>**/*Spec.groovy</include> </includes> </configuration> </plugin>
  • 8. 7 Sp●ck Specifications import spock.lang.Specification class FirstSpec extends Specification { def "length of Carmaker name"() { expect: "BMW".length() == 3 } }  Spock tests are written in groovy.  Semicolons are optional.  Method names follow def keyword and can be string.  Every Spock test class is called a Specification because it extends spock.lang.Specification class. By convention, they end with Spec.  A test method in a Specification is called a feature method, which in turn is equivalent to a JUnit test.  Feature methods are public.
  • 9. 8 Block Taxonomy Block Use given: Used for creating objects, setting up data, launching web pages, logging in before testing access controlled functionality, etc. setup: an alias of given: when: Controls the behavior being tested like initiating an action by a mocked object, interacting with an element on a webpage, etc. A when: block must be followed by a then: block. then: Makes assertions about the results of when: block. Requires a preceding when: block expect: Makes assertions without requiring when: block. Can be used to check the initial states of objects or preconditions of when: block. cleanup: Allows a safe tear-down of resources. Analogous to finally block in Java. where: Used for parametrized feature methods and listing data tables and: Used to extend a preceding block. Useful to break a huge expect: or when: block into smaller readable blocks
  • 10. 9 Sp●ck Specifications: A Taste of DSL Consider the following JIRA story – Create a utility to sum the digits of an integer to unit Acceptance Criteria Given When Then Number = 1234 Digits are summed Result = 1 Number = 15678 Result = 9 Number = -35567 Result = 8 Number = 0 Result = 0
  • 11. SP●CK SPECIFICATIONS: A TASTE OF DSL 10 The Spock specification for the aforementioned story can be written as – import spock.lang.Specification class UnitSumTest extends Specification { def "Test summation to a unit" () { given: def sum = new UnitSum() expect: sum.getUnitSum(input) == output where: input | output 1234 | 1 15678 | 9 -35567 | 8 0 | 0 } } Note the relative similarity between story and test, both describing the same behavior.
  • 12. 11 Sp●ck Specifications: Grouped Assertions Consider a Java class – public class User { ...attributes public User(String username) { this.username = username; this.following = new ArrayList<>(); this.posts = new ArrayList<>(); this.registered = Instant.now(); } ...getters and setters }
  • 13. SP●CK SPECIFICATIONS: GROUPED ASSERTIONS 12 Instead of asserting for individual properties one by one, the assertions can be grouped as follows, using Spock’s with method – import spock.lang.Specification import java.time.Instant class GroupedAssertionsSpec extends Specification { def "Multiple Assertions on an Object"() { given: def user = new User("Emma") expect: with(user) { username == "Emma" following.isEmpty() posts.isEmpty() registered instanceof Instant } } }
  • 14. 13 Sp●ck Specifications: Expecting Exceptions import spock.lang.Specification class ExpectExceptionSpec extends Specification { def "Expect StringIndexOutOfBoundsException"() { setup: def str = "Grace is Eternal" when: str.getAt(43) then: thrown(StringIndexOutOfBoundsException) } }  thrown method will pass only if exception is thrown in when: block
  • 15. 14 Sp●ck Specifications: Interrogating Exceptions import spock.lang.Specification class InterrogateExceptionSpec extends Specification { def "Interrogate ArithmeticException"() { given: def num = 10 def zero = 0 when: num / zero then: def e = thrown(ArithmeticException) e.message == "Division by zero" } }  This test passes iff ArithmeticException is thrown and the message matches.
  • 16. 15 Sp●ck Specifications: Unrolling import spock.lang.Specification class UnrollingSpec extends Specification { def "Test for Palindrome" () { given: def palindrome = new SimplePalindrome() expect: palindrome.isPalindrome(str) == expected where: str | expected "BOB" | true "vIv" | true "A" | true "Holly" | false } } • Without unrolling the entire specification runs without informing precisely which iterations failed or passed • A series of exceptions are thrown and developer has to figure out which exception corresponds to which test failure
  • 17. SP●CK SPECIFICATIONS: UNROLLING 16 The same specification with unrolling enabled – import spock.lang.Specification import spock.lang.Unroll class UnrollingSpec extends Specification { @Unroll("is #str a palindrome? #answer") def "Test for Palindrome" () { given: def palindrome = new SimplePalindrome() expect: palindrome.isPalindrome(str) == expected where: str | expected "BOB" | true "vIv" | true "A" | true "Holly" | false answer = expected ? "YES" : "NO" } }
  • 18. 17 Specification Lifecycle: Fixture Methods Name When run Similar to JUnit setup() Before each test @Before cleanup() After each test @After setupSpec() Before first test @BeforeClass cleanupSpec() After last test @AfterClass The lifeline of various methods in a Specification – 1. setupSpec() 2. setup() 3. feature method 1() 4. cleanup() 5. setup() 6. feature method 2() 7. cleanup() 8. ... 9. cleanupSpec()
  • 19. 18 Resource Sharing import spock.lang.Shared import spock.lang.Specification class ArrayListSpec extends Specification { @Shared list = new ArrayList<String>() def "check if list is clear"() { list.add("Allspark") when: list.clear() then: list.size() == 0 } }  Resources that are needed in several features can be declared as @Shared
  • 20. 19 Resource Management import spock.lang.Shared import spock.lang.Specification import java.sql.Connection import java.sql.DriverManager import java.sql.ResultSet import java.sql.Statement class DatabaseSpec extends Specification { private final url = "jdbc:mariadb://localhost:3306/spring" private final username = "erin" private final password = "richards" @Shared Connection connection def setup() { connection = DriverManager.getConnection(url, username, password) }
  • 21. RESOURCE MANAGEMENT 20 def "DB test"() { given: Statement statement = connection.createStatement() final query = "select * from book where book_id = 1" when: ResultSet resultSet = statement.executeQuery(query) then: resultSet.getMetaData().getColumnCount() > 1 cleanup: resultSet.close() } def cleanup() { connection.close() } }
  • 22. 21 Specification Lifecycle: Revisited Consider two Specifications SuperSpec and SubSpec, where SubSpec is a child of abstract SuperSpec. When SubSpec is tested, the Spock lifecycle follows the following lifeline – 1. super setupSpec() 2. sub setupSpec() 3. super setup() 4. sub setup() 5. sub feature method 1() 6. sub cleanup() 7. super cleanup() 8. super setup() 9. sub setup() 10. sub feature method 2() 11. sub cleanup() 12. super cleanup() 13. ... 14. sub cleanupSpec() 15. super cleanupSpec()  Execution of the setupSpec and setup methods proceeds down the inheritance tree  Execution of the cleanupSpec and cleanup methods proceeds up the inheritance tree
  • 23. 22 Specification Inheritance import spock.lang.* import java.sql.* abstract class DatabaseSpec extends Specification { private final url = "jdbc:mariadb://localhost:3306/spring" private final username = "erin" private final password = "richards" @Shared Connection connection def setup() { connection = DriverManager.getConnection(url, username, password) } def cleanup() { connection.close() } }
  • 24. SPECIFICATION INHERITANCE 23 import java.sql.ResultSet import java.sql.Statement class BookQuerySpec extends DatabaseSpec { private static ResultSet resultSet def "DB test"() { given: Statement statement = connection.createStatement() final query = "select * from book where book_id = 1" when: resultSet = statement.executeQuery(query) then: resultSet.getMetaData().getColumnCount() > 1 } def cleanup() { resultSet.close() } }
  • 25. 24 Conditional Testing Annotations for conditional testing of Specifications/feature methods – @Ignore Forces the test runner to skip a particular feature method or specification class @IgnoreRest Isolates a single feature method or specification class that should be executed while the rest of the suite is skipped @PendingFeature A variant of @Ignore. Feature methods annotated with @PendingFeature are executed with the expectation that they will fail. If a feature method annotated with @PendingFeature actually passes, that is reported as an error.
  • 26. 25 Sp●ck Diagnostics import spock.lang.Specification class DiagnosticsSpec extends Specification { def "check string length"() { given: def str = new StringBuilder() expect: str.append("Hello").append("-World").replaceAll("-", ", ").toString() == "Hello World" } }  given describes the pre-condition  expect is the assertion
  • 27. SP●CK DIAGNOSTICS 26 When DiagnosticsSpec is run, the following message is displayed – Condition not satisfied: str.append("Hello").append("-World").replaceAll("-", ", ").toString() == "Hello World" | | | | | | | Hello-World Hello-World Hello, World | false Hello-World | 1 difference (91% similarity) | Hello(,) World | Hello(-) World Hello, World Expected :Hello World Actual :Hello, World <Click to see difference> at in.naiyer.spock.basic.DiagnosticsSpec.check string length(DiagnosticsSpec.groovy:12)  The values are evaluated at the end of every expression.  The most relevant line of stacktrace is printed.  A diff window is available to compare the expected and actual values.
  • 29. 28 What Next?  @Stepwise Specifications  Integration Testing  Functional Testing of REST services  Testing Reactive applications  Browser Automation and E2E Testing with Selenium & Geb  Build Pipelining with Spock  Code coverage from Spock  Spock integration with TeamCity and JIRA  Spock Extensions  Testing JavaScript, Scala, Kotlin, Groovy, etc. with Spock
  • 30. 29 References Darwin, Ian: Java Testing for Developers (O’Reilly, 2016) Fletcher, Rob: Spock: Up and Running (O’Reilly, 2017) Kapelonis, Konstantinos: Java Testing with Spock (Manning, 2016) Kapelonis, Konstantinos: Spock: A Logical Framework for Enterprise Testing (GR8Conf US, 2014) Niederwieser, Peter: Spock Framework Example Project (Github, 2012) Niederwieser, Peter: Testing Java, Groovy, Spring and Web Applications with Spock (springone, 2014) Spock Framework Website: http://spockframework.org
  • 31. 30 Contacts Peter Niederwieser Luke Daley Rob Fletcher Konstantinos Kapelonis Stack Overflow @ldaley @rfletcherEW @codepipes http://ldaley.com/ http://codepipes.com/