SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code EffectivelyAndres Almiray
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with SpockDmitry 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 1Kirill Rozov
 
Software engineering ⊇ Software testing
Software engineering ⊇ Software testingSoftware engineering ⊇ Software testing
Software engineering ⊇ Software testingPavel Tcholakov
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS ProgrammersDavid Rodenas
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42Yevhen Bobrov
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書くShoichi Matsuda
 
ES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorES3-2020-P3 TDD Calculator
ES3-2020-P3 TDD CalculatorDavid Rodenas
 
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 RestyGWTDavid Chandler
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 

La actualidad más candente (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 a 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 TestSchalk Cronjé
 
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
 
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.docxtidwellveronique
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfShaiAlmog1
 
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 CodeDaniel Wellman
 
Android testing
Android testingAndroid testing
Android testingSean 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 TestsTomek Kaczanowski
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
Spocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderSpocktacular Testing - Russel Winder
Spocktacular Testing - Russel WinderJAXLondon2014
 
Spocktacular Testing
Spocktacular TestingSpocktacular Testing
Spocktacular TestingRussel Winder
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about GradleEvgeny Goldin
 

Similar a 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 - Russel Winder
Spocktacular Testing - Russel WinderSpocktacular Testing - Russel Winder
Spocktacular Testing - Russel Winder
 
Spocktacular Testing
Spocktacular TestingSpocktacular Testing
Spocktacular Testing
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
 

Más de 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 EffectiveNaresha 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 TestContainersNaresha K
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with MicronautNaresha 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 TestContainersNaresha K
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy WayNaresha 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 PracticesNaresha 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 ProgrammingNaresha 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 MicronautNaresha 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 LambdaNaresha K
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring PatternsNaresha 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 MicronautNaresha K
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with GroovyNaresha 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 EffectiveNaresha 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 PracticesNaresha 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 JavaNaresha K
 
GORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitGORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitNaresha K
 

Más de 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
 

Último

How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 

Último (20)

How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

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.