SlideShare a Scribd company logo
1 of 40
Download to read offline
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

Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
Dmitry Voloshko
 

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

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
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
tidwellveronique
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
Tino Isnich
 
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 - 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
 

More from 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

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Recently uploaded (20)

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-...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
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 ...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
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
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 

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.