SlideShare a Scribd company logo
23 September 2021
The Groovy Way of Testing
with Spock
Naresha K
@naresha_k

https://blog.nareshak.com/
About me
Developer, Architect &
Tech Excellence Coach
Founder & Organiser
Bangalore Groovy User
Group
Intention Conveying
import org.junit.jupiter.api.DisplayName;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class SampleJupiterTest {

@Test

@DisplayName("This test should pass if project is setup properly")

public void thisTestShouldPassIfProjectIsSetupProperly() {

assertThat(true).isTrue();

}

}
https://martinfowler.com/bliki/BeckDesignRules.html
import spock.lang.Specification

class SampleSpecification extends Specification {

void "This test should pass if project is setup properly"() {

expect:

true

}

}
BDD Style
Given - When - Then
def “files added to a bucket are available in the bucket”() {

given:

def filePath = Paths.get("src/test/resources/car.jpg")

InputStream stream = Files.newInputStream(filePath)

when:

fileStorageService.storeFile(TARGET_BUCKET, "vehicles/123.jpg", stream)

then:

amazonS3Service.exists(TARGET_BUCKET, "vehicles/123.jpg")

}
def "file can be stored in s3 storage and read"() {

given:

def filePath = Paths.get("src/test/resources/car.jpg")

InputStream stream = Files.newInputStream(filePath)

when:

fileStorageService.storeFile(TARGET_BUCKET, "vehicles/123.jpg", stream)

then:

amazonS3Service.exists(TARGET_BUCKET, "vehicles/123.jpg")

when:

File file = fileStorageService.readFile(TARGET_BUCKET, "vehicles/123.jpg",

Files.createTempFile(null, null).toAbsolutePath().toString())

then:

file

and:

file.newInputStream().bytes
=
=
filePath.bytes

}
Power Asserts
void "list assertion example"() {

given:

List<Integer> numbers = [1, 2, 3]

when:

/
/
List<Integer> result = numbers.collect { it * 2}

List<Integer> result = [2, 2, 6]

then:

result
=
=
[2, 4, 6]

}
Condition not satis
fi
ed:

result == [2, 4, 6]

| |

| false

[2, 2, 6]
void "list contains expected element"() {

expect:

10 in [2, 4, 6]

}
Condition not satis
fi
ed:

10 in [2, 4, 6]

|

false
void "assert all"() {

expect:

verifyAll {

10 in [2, 4, 6]

12 in [2, 4, 6]

}

}
Multiple Failures (2 failures)

	 org.spockframework.runtime.ConditionNotSatis
fi
edError: Condition not satis
fi
ed:

10 in [2, 4, 6]

|

false

	 org.spockframework.runtime.ConditionNotSatis
fi
edError: Condition not satis
fi
ed:

12 in [2, 4, 6]

|

false
void "assert object by extracting field"() {

when:

List<Person> authors = [new Person(firstName: 'James', lastName: 'Gosling'),

new Person(firstName: 'Kent', lastName: 'Beck')]

then:

authors*.lastName
=
=
['Gosling', 'Beck ']

}
Condition not satis
fi
ed:

authors*.lastName == ['Gosling', 'Beck ']

| | |

| | false

| [Gosling, Beck]

[Person(James, Gosling), Person(Kent, Beck)]
void "assert with containsAll"() {

when:

List<Integer> numbers = [2, 4, 6]

then:

numbers.containsAll([10, 12])

}
Condition not satis
fi
ed:

numbers.containsAll([10, 12])

| |

| false

[2, 4, 6]
Data-Driven Testing
@Unroll

void "#a + #b should be #expectedSum"() {

when:

def sum = a + b

then:

sum
=
=
expectedSum

where:

a | b | expectedSum

10 | 10 | 20

20 | 20 | 40

}
Ordered Execution of Tests
@Stepwise

class OrderedSpecification extends Specification {

void "test 1"() {

expect:

true

}

void "test 2"() {

expect:

true

}

void "test 3"() {

expect:

true

}

}
@Stepwise

class OrderedSpecification extends Specification {

void "test 1"() {

expect:

true

}

void "test 2"() {

expect:

false

}

void "test 3"() {

expect:

true

}

}
Mocking
@Canonical

class TalkPopularityService {

AudienceCountService audienceCountService

public boolean isPopularTalk(String talk) {

def count = audienceCountService.getAudienceCount(talk)

count > 100 ? true : false

}

}
interface AudienceCountService {

int getAudienceCount(String talk)

}
class TalkPopularityServiceSpec extends Specification {

private AudienceCountService audienceCountService = Mock()

private TalkPopularityService talkPopularityService =

new TalkPopularityService(audienceCountService)

void "when audience count is 200 talk should be considered popular"() {

given:

String talk = "Whats new in Groovy 4"

when:

boolean isPopular = talkPopularityService.isPopularTalk(talk)

then:

isPopular
=
=
true

and:

1 * audienceCountService.getAudienceCount(talk)
>
>
200

}

void "when audience count is 90 talk should be considered not popular"() {

given:

String talk = "Some talk"

when:

boolean isPopular = talkPopularityService.isPopularTalk(talk)

then:

isPopular
=
=
false

and:

1 * audienceCountService.getAudienceCount(talk)
>
>
90

}

}
Spock 1.x - JUnit 4 Compatibility
https://github.com/naresha/junitspock
public class Sputnik extends Runner 

implements Filterable, Sortable {

/
/
code

}
Spock - JUnit 5 Compatibility
public class SpockEngine extends HierarchicalTestEngine<SpockExecutionContext> {

@Override

public String getId() {

return "spock";

}

/
/
more code

}
@Shared
public class SampleTest {

private StateHolder stateHolder = new StateHolder();

@Test

void test1() {

/
/
use stateHolder

}

@Test

void test2() {

/
/
use stateHodler

}

}
public class StateHolder {

public StateHolder() {

System.out.println("Instantiating StateHolder");

}

}
public class SampleTest {

private StateHolder stateHolder = new StateHolder();

@Test

void test1() {

/
/
use stateHolder

}

@Test

void test2() {

/
/
use stateHodler

}

}
public class StateHolder {

public StateHolder() {

System.out.println("Instantiating StateHolder");

}

}
@BeforeEach

private void setup() {

stateHolder = new StateHolder();

}
public class SampleSharedStateTest {

private StateHolder stateHolder;

@BeforeAll

void beforeAll() {

stateHolder = new StateHolder();

}

@Test

void test1() {

/
/
use shared stateHolder

System.out.println(stateHolder);

}

@Test

void test2() {

/
/
use shared stateHodler

System.out.println(stateHolder);

}

}
public class SampleSharedStateTest {

private StateHolder stateHolder;

@BeforeAll

void beforeAll() {

stateHolder = new StateHolder();

}

@Test

void test1() {

/
/
use shared stateHolder

System.out.println(stateHolder);

}

@Test

void test2() {

/
/
use shared stateHodler

System.out.println(stateHolder);

}

}
@BeforeAll method 'void
com.nareshak.demo.SampleSharedStateTest.beforeAll()'
must be static unless the test class is annotated with
@TestInstance(Lifecycle.PER_CLASS).
public class SampleSharedStateTest {

private static StateHolder stateHolder;

@BeforeAll

static void beforeAll() {

stateHolder = new StateHolder();

}

@Test

void test1() {

/
/
use shared stateHolder

System.out.println(stateHolder);

}

@Test

void test2() {

/
/
use shared stateHodler

System.out.println(stateHolder);

}

}
Instantiating StateHolder

com.nareshak.demo.StateHolder@5bea6e0

com.nareshak.demo.StateHolder@5bea6e0
class SharedStateSpec extends Specification{

@Shared

private StateHolder stateHolder = new StateHolder()

void "spec 1"() {

println stateHolder

expect:

true

}

void "spec 2"() {

println stateHolder

expect:

true

}

}
com.nareshak.demo.StateHolder@53708326

com.nareshak.demo.StateHolder@53708326
class SharedStateSpec extends Specification{

@Shared

private StateHolder stateHolder = new StateHolder()

void "spec 1"() {

println stateHolder

expect:

true

}

void "spec 2"() {

println stateHolder

expect:

true

}

}
com.nareshak.demo.StateHolder@53708326

com.nareshak.demo.StateHolder@53708326
@Shared

private StateHolder stateHolder

void setupSpec() {

stateHolder = new StateHolder()

}
And
The most important Reason
???
https://github.com/naresha/apachecon2021spock
Thank You

More Related Content

What's hot

Spock
SpockSpock
Testing in-groovy
Testing in-groovyTesting in-groovy
Testing in-groovy
Franz Allan See
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
Andres Almiray
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
Dmitry Voloshko
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1
Kirill Rozov
 
Software engineering ⊇ Software testing
Software engineering ⊇ Software testingSoftware engineering ⊇ Software testing
Software engineering ⊇ Software testing
Pavel Tcholakov
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
David Rodenas
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
Yevhen Bobrov
 
Unit Testing in Kotlin
Unit Testing in KotlinUnit Testing in Kotlin
Unit Testing in Kotlin
Egor Andreevich
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書く
Shoichi Matsuda
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD Calculator
David Rodenas
 
Spock framework
Spock frameworkSpock framework
Spock framework
Djair Carvalho
 
Unit testing
Unit testingUnit testing
Unit testing
davidahaskins
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
David Chandler
 
Spock
SpockSpock
Easy Button
Easy ButtonEasy Button
Easy Button
Adam Dale
 
Testing with PostgreSQL
Testing with PostgreSQLTesting with PostgreSQL
Testing with PostgreSQL
Shawn Sorichetti
 
Celery
CeleryCelery
Code Samples
Code SamplesCode Samples
Code Samples
Bill La Forge
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
Anton Udovychenko
 

What's hot (20)

Spock
SpockSpock
Spock
 
Testing in-groovy
Testing in-groovyTesting in-groovy
Testing in-groovy
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1
 
Software engineering ⊇ Software testing
Software engineering ⊇ Software testingSoftware engineering ⊇ Software testing
Software engineering ⊇ Software testing
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Unit Testing in Kotlin
Unit Testing in KotlinUnit Testing in Kotlin
Unit Testing in Kotlin
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書く
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD Calculator
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Unit testing
Unit testingUnit testing
Unit testing
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
 
Spock
SpockSpock
Spock
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
Testing with PostgreSQL
Testing with PostgreSQLTesting with PostgreSQL
Testing with PostgreSQL
 
Celery
CeleryCelery
Celery
 
Code Samples
Code SamplesCode Samples
Code Samples
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 

Similar to The Groovy Way of Testing with Spock

Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
Schalk Cronjé
 
Java objects on steroids
Java objects on steroidsJava objects on steroids
Java objects on steroids
Romain Rochegude
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
Tsuyoshi Yamamoto
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
Tiago de Freitas Lima
 
Google guava
Google guavaGoogle guava
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
 
Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!
Julien Truffaut
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
tidwellveronique
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
Schalk Cronjé
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
ShaiAlmog1
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
Daniel Wellman
 
Android testing
Android testingAndroid testing
Android testing
Sean Tsai
 
FluentLeniumで困った話
FluentLeniumで困った話FluentLeniumで困った話
FluentLeniumで困った話
Yuuki Ooguro
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
Tomek Kaczanowski
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
Dmitry Buzdin
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
Tino Isnich
 
Spocktacular Testing
Spocktacular TestingSpocktacular Testing
Spocktacular Testing
Russel Winder
 
Spocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderSpocktacular Testing - Russel Winder
Spocktacular Testing - Russel Winder
JAXLondon2014
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
Evgeny Goldin
 

Similar to The Groovy Way of Testing with Spock (20)

Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Java objects on steroids
Java objects on steroidsJava objects on steroids
Java objects on steroids
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 
Google guava
Google guavaGoogle guava
Google guava
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!Implicit parameters, when to use them (or not)!
Implicit parameters, when to use them (or not)!
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Android testing
Android testingAndroid testing
Android testing
 
FluentLeniumで困った話
FluentLeniumで困った話FluentLeniumで困った話
FluentLeniumで困った話
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Spocktacular Testing
Spocktacular TestingSpocktacular Testing
Spocktacular Testing
 
Spocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderSpocktacular Testing - Russel Winder
Spocktacular Testing - Russel Winder
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
 

More from Naresha K

Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
Naresha K
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
Naresha K
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with Micronaut
Naresha K
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
Naresha K
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy Way
Naresha K
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Naresha K
 
What's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingWhat's in Groovy for Functional Programming
What's in Groovy for Functional Programming
Naresha K
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Naresha K
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Naresha K
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Naresha K
 
Implementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautImplementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with Micronaut
Naresha K
 
Groovy - Why and Where?
Groovy  - Why and Where?Groovy  - Why and Where?
Groovy - Why and Where?
Naresha K
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS Lambda
Naresha K
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring Patterns
Naresha K
 
Implementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautImplementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with Micronaut
Naresha K
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
Naresha K
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
Naresha K
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good Practices
Naresha K
 
Beyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaBeyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in Java
Naresha K
 
GORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitGORM - The polyglot data access toolkit
GORM - The polyglot data access toolkit
Naresha K
 

More from Naresha K (20)

Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with Micronaut
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy Way
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good Practices
 
What's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingWhat's in Groovy for Functional Programming
What's in Groovy for Functional Programming
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
 
Implementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautImplementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with Micronaut
 
Groovy - Why and Where?
Groovy  - Why and Where?Groovy  - Why and Where?
Groovy - Why and Where?
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS Lambda
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring Patterns
 
Implementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautImplementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with Micronaut
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good Practices
 
Beyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaBeyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in Java
 
GORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitGORM - The polyglot data access toolkit
GORM - The polyglot data access toolkit
 

Recently uploaded

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 

Recently uploaded (20)

How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 

The Groovy Way of Testing with Spock

  • 1. 23 September 2021 The Groovy Way of Testing with Spock Naresha K @naresha_k https://blog.nareshak.com/
  • 2. About me Developer, Architect & Tech Excellence Coach Founder & Organiser Bangalore Groovy User Group
  • 3.
  • 5. import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class SampleJupiterTest { @Test @DisplayName("This test should pass if project is setup properly") public void thisTestShouldPassIfProjectIsSetupProperly() { assertThat(true).isTrue(); } }
  • 7. import spock.lang.Specification class SampleSpecification extends Specification { void "This test should pass if project is setup properly"() { expect: true } }
  • 8. BDD Style Given - When - Then
  • 9. def “files added to a bucket are available in the bucket”() { given: def filePath = Paths.get("src/test/resources/car.jpg") InputStream stream = Files.newInputStream(filePath) when: fileStorageService.storeFile(TARGET_BUCKET, "vehicles/123.jpg", stream) then: amazonS3Service.exists(TARGET_BUCKET, "vehicles/123.jpg") }
  • 10. def "file can be stored in s3 storage and read"() { given: def filePath = Paths.get("src/test/resources/car.jpg") InputStream stream = Files.newInputStream(filePath) when: fileStorageService.storeFile(TARGET_BUCKET, "vehicles/123.jpg", stream) then: amazonS3Service.exists(TARGET_BUCKET, "vehicles/123.jpg") when: File file = fileStorageService.readFile(TARGET_BUCKET, "vehicles/123.jpg", Files.createTempFile(null, null).toAbsolutePath().toString()) then: file and: file.newInputStream().bytes = = filePath.bytes }
  • 12. void "list assertion example"() { given: List<Integer> numbers = [1, 2, 3] when: / / List<Integer> result = numbers.collect { it * 2} List<Integer> result = [2, 2, 6] then: result = = [2, 4, 6] } Condition not satis fi ed: result == [2, 4, 6] | | | false [2, 2, 6]
  • 13. void "list contains expected element"() { expect: 10 in [2, 4, 6] } Condition not satis fi ed: 10 in [2, 4, 6] | false
  • 14. void "assert all"() { expect: verifyAll { 10 in [2, 4, 6] 12 in [2, 4, 6] } } Multiple Failures (2 failures) org.spockframework.runtime.ConditionNotSatis fi edError: Condition not satis fi ed: 10 in [2, 4, 6] | false org.spockframework.runtime.ConditionNotSatis fi edError: Condition not satis fi ed: 12 in [2, 4, 6] | false
  • 15. void "assert object by extracting field"() { when: List<Person> authors = [new Person(firstName: 'James', lastName: 'Gosling'), new Person(firstName: 'Kent', lastName: 'Beck')] then: authors*.lastName = = ['Gosling', 'Beck '] } Condition not satis fi ed: authors*.lastName == ['Gosling', 'Beck '] | | | | | false | [Gosling, Beck] [Person(James, Gosling), Person(Kent, Beck)]
  • 16. void "assert with containsAll"() { when: List<Integer> numbers = [2, 4, 6] then: numbers.containsAll([10, 12]) } Condition not satis fi ed: numbers.containsAll([10, 12]) | | | false [2, 4, 6]
  • 18. @Unroll void "#a + #b should be #expectedSum"() { when: def sum = a + b then: sum = = expectedSum where: a | b | expectedSum 10 | 10 | 20 20 | 20 | 40 }
  • 20. @Stepwise class OrderedSpecification extends Specification { void "test 1"() { expect: true } void "test 2"() { expect: true } void "test 3"() { expect: true } }
  • 21. @Stepwise class OrderedSpecification extends Specification { void "test 1"() { expect: true } void "test 2"() { expect: false } void "test 3"() { expect: true } }
  • 23. @Canonical class TalkPopularityService { AudienceCountService audienceCountService public boolean isPopularTalk(String talk) { def count = audienceCountService.getAudienceCount(talk) count > 100 ? true : false } } interface AudienceCountService { int getAudienceCount(String talk) }
  • 24. class TalkPopularityServiceSpec extends Specification { private AudienceCountService audienceCountService = Mock() private TalkPopularityService talkPopularityService = new TalkPopularityService(audienceCountService) void "when audience count is 200 talk should be considered popular"() { given: String talk = "Whats new in Groovy 4" when: boolean isPopular = talkPopularityService.isPopularTalk(talk) then: isPopular = = true and: 1 * audienceCountService.getAudienceCount(talk) > > 200 } void "when audience count is 90 talk should be considered not popular"() { given: String talk = "Some talk" when: boolean isPopular = talkPopularityService.isPopularTalk(talk) then: isPopular = = false and: 1 * audienceCountService.getAudienceCount(talk) > > 90 } }
  • 25. Spock 1.x - JUnit 4 Compatibility https://github.com/naresha/junitspock
  • 26. public class Sputnik extends Runner implements Filterable, Sortable { / / code }
  • 27. Spock - JUnit 5 Compatibility
  • 28. public class SpockEngine extends HierarchicalTestEngine<SpockExecutionContext> { @Override public String getId() { return "spock"; } / / more code }
  • 30. public class SampleTest { private StateHolder stateHolder = new StateHolder(); @Test void test1() { / / use stateHolder } @Test void test2() { / / use stateHodler } } public class StateHolder { public StateHolder() { System.out.println("Instantiating StateHolder"); } }
  • 31. public class SampleTest { private StateHolder stateHolder = new StateHolder(); @Test void test1() { / / use stateHolder } @Test void test2() { / / use stateHodler } } public class StateHolder { public StateHolder() { System.out.println("Instantiating StateHolder"); } } @BeforeEach private void setup() { stateHolder = new StateHolder(); }
  • 32. public class SampleSharedStateTest { private StateHolder stateHolder; @BeforeAll void beforeAll() { stateHolder = new StateHolder(); } @Test void test1() { / / use shared stateHolder System.out.println(stateHolder); } @Test void test2() { / / use shared stateHodler System.out.println(stateHolder); } }
  • 33. public class SampleSharedStateTest { private StateHolder stateHolder; @BeforeAll void beforeAll() { stateHolder = new StateHolder(); } @Test void test1() { / / use shared stateHolder System.out.println(stateHolder); } @Test void test2() { / / use shared stateHodler System.out.println(stateHolder); } } @BeforeAll method 'void com.nareshak.demo.SampleSharedStateTest.beforeAll()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).
  • 34. public class SampleSharedStateTest { private static StateHolder stateHolder; @BeforeAll static void beforeAll() { stateHolder = new StateHolder(); } @Test void test1() { / / use shared stateHolder System.out.println(stateHolder); } @Test void test2() { / / use shared stateHodler System.out.println(stateHolder); } } Instantiating StateHolder com.nareshak.demo.StateHolder@5bea6e0 com.nareshak.demo.StateHolder@5bea6e0
  • 35. class SharedStateSpec extends Specification{ @Shared private StateHolder stateHolder = new StateHolder() void "spec 1"() { println stateHolder expect: true } void "spec 2"() { println stateHolder expect: true } } com.nareshak.demo.StateHolder@53708326 com.nareshak.demo.StateHolder@53708326
  • 36. class SharedStateSpec extends Specification{ @Shared private StateHolder stateHolder = new StateHolder() void "spec 1"() { println stateHolder expect: true } void "spec 2"() { println stateHolder expect: true } } com.nareshak.demo.StateHolder@53708326 com.nareshak.demo.StateHolder@53708326 @Shared private StateHolder stateHolder void setupSpec() { stateHolder = new StateHolder() }
  • 38.