SlideShare uma empresa Scribd logo
1 de 18
SPOCK
Testing framework
Presented By
Gajraj Kalburgi
Introduction
• Spock is a testing framework.
• Highly expressive specification language.
• Inspired by Junit, Jmock, Rspec, Groovy, Scala, Vulcans.
Spec structure
• Specs are written in groovy and extends Specification from spock.
class MySpec extends Specification {
// fields
// fixture methods
// feature methods
// helper methods
}
Fields
• Declaration of objects.
• Every feature methods gets it’s own object at runtime.
def obj1, obj2
@Shared
• It will allow to share objects with in features.
• Needs when object creation is huge task (memory / time).
• Required when we want to use fields in where block.
@Shared obj1, obj2
Fixture Methods
Spock Junit
def setup @Before
def cleanup @After
def setupSpec @BeforeClass
def cleanupSpec @AfterClass
Feature Methods
• Feature methods are the heart of a specification.
• Conceptually, a feature method consists of four phases:
1. Set up the feature’s fixture
2. Provide a stimulus to the system under specification
3. Describe the response expected from the system
4. Clean up the feature’s fixture
• Above phases are described using blocks.
def “Feature name”() {
// blocks
}
Blocks
setup: Setup feature data, object state, define mock object behavior.
given: Alias for setup block.
when: Stimulation(actual call, can be void call)
then: Assertion, Condition testing
expect: It’s combination of when and then block (Make actual call and do
result assertion, Function must return some value for assertion)
cleanup: Cleanup feature data, object state
where: Streamline data used in feature, Feature will be executed multiple
time depended on where block data.
Helper Methods
• Helper methods used to write common logic for features.
• It can have conditions for asserting in then block.
• It can have mock object behavior to use in given or setup block.
• It can be used to give name for common code block.
Data driven testing
Data table
def “Math.max”() {
expect:
Math.max(a, b) == c
where:
a | b || c
8 | 5 || 8
10 | 14 || 14
}
Data driven testing
Data pipe
def “Math.max”() {
expect:
Math.max(a, b) == c
where:
a << [8, 10, 25]
b << [3, 23, 18]
c << [8, 23, 25]
}
@Unroll
• It’s defines how feature is reported.
• Each data defined in where will be reported as separate test.
• It allows dynamic naming for features.
• We can use members used in features to change feature name.
@Unroll
def “Math.max(#a, #b) == #c”() {
expect:
Math.max(a, b) == c
where:
a | b || c
8 | 5 || 8
10 | 14 || 14
}
Extensions
@Ignore : Ignores feature.
@IgnoreRest : Ignores all features except this. (useful to test only one feature.
@IgnoreIf : Ignore feature with condition.
@Require : Ignore feature with condition (Inverted @IgnoreIf)
@PendingFeature : To suggest feature is pending. (Skips test when at least one iteration fails,
If all iteration fails test will be reported as failed.)
@Stepwise : Execute all feature in a sequence as they written. If any test fails it will skip
remaining tests in class.
@Timeout : Timeout time for feature to execute.
@FailsWith : Some feature fails due to bugs in production code. This annotation will
abruptly complete execution.
@FailsWith(“XYZ api not working now”)
Specification
thrown : Asserts that exception thrown.
notThrown : Asserts that specified exception is not thrown.
noExceptionThrown : Asserts that no exception is thrown.
old : Used to get field value before when block’s execution.
with : To make multiple condition/operation with object.
verifyAll : Asserts all conditions.
Mock
Mock factory method creates mock object.
class MySpec extends Specification {
def mockObj = Mock(MockClass)
def targetObj = new TargetClass(mockObj)
def “Hello World Feature”() {
given: “Hello World Feature”
mockObj.mockFunction(“Hello”) >> “Hello World !!”
when: “Hello World Feature”
def result = targetObj.call(“Hello”)
then: “Hello World Feature”
result == “Hello World !!”
}
}
Stub
We can define mock object behavior in setup or given block. It’s called
stubbing.
given:
mockobject.function(“Hello”) >> “Hello world !”
mockobject.function(_ as String) >> [“Hello”,“world !”]
mockobject._(_) >> { throw new Exception() }
mockobject./f.*n/(!null) >>> [“ONE”,“TWO”] >> {throw new Exception() } >> “ALL”
mockobject.function({ it.size() > 3 })
mockobject.function({ [“hello”].contains(it) })
Verify
We can verify mock interactions in then block.
then:
1 * mockobject.function(“hello”)
(1..2) * _.function(_ as String)
(_..5) * mockobject._(_)
(2.._) * mockobject./f.*n/(!null)
_ * mockobject.function({ it.size() > 3 })
0 * mockobject.function({ [“hello”].contains(it) })
Combine Stub and Verify
given:
1 * mockobject.function(“Hello”) >> “Hello world !”
(1..2) * mockobject.function(_ as String) >> [“Hello”,“world !”]
(_..5) * mockobject._(_) >> { throw new Exception() }
(2.._) * mockobject./f.*n/(!null) >>> [“ONE”,“TWO”] >> {throw new Exception() } >> “ALL”
_ * mockobject.function({ it.size() > 3 })
0 * mockobject.function({ [“hello”].contains(it) })
Hamcrest Support
We can use hamcrest for assert.
then:
HamcrestSupport.that(result,
IsIterableContaininInAnyOrder.containsInAnyOrder( element1, element2 ))

Mais conteúdo relacionado

Mais procurados

Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using SpockAnuj Aneja
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Graham Dumpleton
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 
Py.test
Py.testPy.test
Py.testsoasme
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 
GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?Patrick Lam
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 

Mais procurados (20)

Spock framework
Spock frameworkSpock framework
Spock framework
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Celery
CeleryCelery
Celery
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Py.test
Py.testPy.test
Py.test
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?GTAC 2014: What lurks in test suites?
GTAC 2014: What lurks in test suites?
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Python unittest
Python unittestPython unittest
Python unittest
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 

Semelhante a Spock

Python mocking intro
Python mocking introPython mocking intro
Python mocking introHans Jones
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
Pocket Talk; Spock framework
Pocket Talk; Spock frameworkPocket Talk; Spock framework
Pocket Talk; Spock frameworkInfoway
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormDavorin Vukelic
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoveragemlilley
 
More topics on Java
More topics on JavaMore topics on Java
More topics on JavaAhmed Misbah
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 

Semelhante a Spock (20)

Spock
SpockSpock
Spock
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Group111
Group111Group111
Group111
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Unit testing
Unit testingUnit testing
Unit testing
 
Easy mock
Easy mockEasy mock
Easy mock
 
Pocket Talk; Spock framework
Pocket Talk; Spock frameworkPocket Talk; Spock framework
Pocket Talk; Spock framework
 
Testing con spock
Testing con spockTesting con spock
Testing con spock
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 

Último

A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityamy56318795
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationHelp Desk Migration
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024vaibhav130304
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAlluxio, Inc.
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfmbmh111980
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)Max Lee
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionMohammed Fazuluddin
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfVictor Lopez
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfDeskTrack
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignNeo4j
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAlluxio, Inc.
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfQ-Advise
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersEmilyJiang23
 

Último (20)

A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
AI Hackathon.pptx
AI                        Hackathon.pptxAI                        Hackathon.pptx
AI Hackathon.pptx
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 

Spock

  • 2. Introduction • Spock is a testing framework. • Highly expressive specification language. • Inspired by Junit, Jmock, Rspec, Groovy, Scala, Vulcans.
  • 3. Spec structure • Specs are written in groovy and extends Specification from spock. class MySpec extends Specification { // fields // fixture methods // feature methods // helper methods }
  • 4. Fields • Declaration of objects. • Every feature methods gets it’s own object at runtime. def obj1, obj2 @Shared • It will allow to share objects with in features. • Needs when object creation is huge task (memory / time). • Required when we want to use fields in where block. @Shared obj1, obj2
  • 5. Fixture Methods Spock Junit def setup @Before def cleanup @After def setupSpec @BeforeClass def cleanupSpec @AfterClass
  • 6. Feature Methods • Feature methods are the heart of a specification. • Conceptually, a feature method consists of four phases: 1. Set up the feature’s fixture 2. Provide a stimulus to the system under specification 3. Describe the response expected from the system 4. Clean up the feature’s fixture • Above phases are described using blocks. def “Feature name”() { // blocks }
  • 7. Blocks setup: Setup feature data, object state, define mock object behavior. given: Alias for setup block. when: Stimulation(actual call, can be void call) then: Assertion, Condition testing expect: It’s combination of when and then block (Make actual call and do result assertion, Function must return some value for assertion) cleanup: Cleanup feature data, object state where: Streamline data used in feature, Feature will be executed multiple time depended on where block data.
  • 8. Helper Methods • Helper methods used to write common logic for features. • It can have conditions for asserting in then block. • It can have mock object behavior to use in given or setup block. • It can be used to give name for common code block.
  • 9. Data driven testing Data table def “Math.max”() { expect: Math.max(a, b) == c where: a | b || c 8 | 5 || 8 10 | 14 || 14 }
  • 10. Data driven testing Data pipe def “Math.max”() { expect: Math.max(a, b) == c where: a << [8, 10, 25] b << [3, 23, 18] c << [8, 23, 25] }
  • 11. @Unroll • It’s defines how feature is reported. • Each data defined in where will be reported as separate test. • It allows dynamic naming for features. • We can use members used in features to change feature name. @Unroll def “Math.max(#a, #b) == #c”() { expect: Math.max(a, b) == c where: a | b || c 8 | 5 || 8 10 | 14 || 14 }
  • 12. Extensions @Ignore : Ignores feature. @IgnoreRest : Ignores all features except this. (useful to test only one feature. @IgnoreIf : Ignore feature with condition. @Require : Ignore feature with condition (Inverted @IgnoreIf) @PendingFeature : To suggest feature is pending. (Skips test when at least one iteration fails, If all iteration fails test will be reported as failed.) @Stepwise : Execute all feature in a sequence as they written. If any test fails it will skip remaining tests in class. @Timeout : Timeout time for feature to execute. @FailsWith : Some feature fails due to bugs in production code. This annotation will abruptly complete execution. @FailsWith(“XYZ api not working now”)
  • 13. Specification thrown : Asserts that exception thrown. notThrown : Asserts that specified exception is not thrown. noExceptionThrown : Asserts that no exception is thrown. old : Used to get field value before when block’s execution. with : To make multiple condition/operation with object. verifyAll : Asserts all conditions.
  • 14. Mock Mock factory method creates mock object. class MySpec extends Specification { def mockObj = Mock(MockClass) def targetObj = new TargetClass(mockObj) def “Hello World Feature”() { given: “Hello World Feature” mockObj.mockFunction(“Hello”) >> “Hello World !!” when: “Hello World Feature” def result = targetObj.call(“Hello”) then: “Hello World Feature” result == “Hello World !!” } }
  • 15. Stub We can define mock object behavior in setup or given block. It’s called stubbing. given: mockobject.function(“Hello”) >> “Hello world !” mockobject.function(_ as String) >> [“Hello”,“world !”] mockobject._(_) >> { throw new Exception() } mockobject./f.*n/(!null) >>> [“ONE”,“TWO”] >> {throw new Exception() } >> “ALL” mockobject.function({ it.size() > 3 }) mockobject.function({ [“hello”].contains(it) })
  • 16. Verify We can verify mock interactions in then block. then: 1 * mockobject.function(“hello”) (1..2) * _.function(_ as String) (_..5) * mockobject._(_) (2.._) * mockobject./f.*n/(!null) _ * mockobject.function({ it.size() > 3 }) 0 * mockobject.function({ [“hello”].contains(it) })
  • 17. Combine Stub and Verify given: 1 * mockobject.function(“Hello”) >> “Hello world !” (1..2) * mockobject.function(_ as String) >> [“Hello”,“world !”] (_..5) * mockobject._(_) >> { throw new Exception() } (2.._) * mockobject./f.*n/(!null) >>> [“ONE”,“TWO”] >> {throw new Exception() } >> “ALL” _ * mockobject.function({ it.size() > 3 }) 0 * mockobject.function({ [“hello”].contains(it) })
  • 18. Hamcrest Support We can use hamcrest for assert. then: HamcrestSupport.that(result, IsIterableContaininInAnyOrder.containsInAnyOrder( element1, element2 ))