SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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

Weitere Àhnliche Inhalte

Was ist angesagt?

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
 
Unit Testing in Kotlin
Unit Testing in KotlinUnit Testing in Kotlin
Unit Testing in KotlinEgor 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 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
 
Easy Button
Easy ButtonEasy Button
Easy ButtonAdam Dale
 
Testing with PostgreSQL
Testing with PostgreSQLTesting with PostgreSQL
Testing with PostgreSQLShawn Sorichetti
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 

Was ist angesagt? (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
 

Ähnlich wie 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é
 
Java objects on steroids
Java objects on steroidsJava objects on steroids
Java objects on steroidsRomain 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
 
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
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle IntroductionDmitry Buzdin
 
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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

KĂŒrzlich hochgeladen

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂anilsa9823
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
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
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
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
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
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
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

KĂŒrzlich hochgeladen (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂
CALL ON ➄8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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 ...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
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
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
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
 
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
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
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...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

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.