SlideShare a Scribd company logo
1 of 21
Download to read offline
Specs2
Library for writing Acceptance And
             Unit Tests

               Piyush Mishra
             Software Consultant
            Knoldus Software LLP
Topics Covered

What is Specs2
The design principles of specs2

Unit Specifications

Acceptance Specifications

Matchers

Runners
What is Specs2
Specs is a DSL in Scala for doing BDD
(Behavior-Driven -Development).
Design Principles of Specs2

Do not use mutable variables
Use a simple structure
Control the dependencies (no cycles)
Control the scope of implicits
Guide to write Unit Specifications
Unit specifications

Extend the org.specs2.mutable.Specification trait

are mutable

 Use should / in format in creates an Example object
containing a Result should creates a group of Example
objects
Creating Unit Specifications
package knoldus.Specs2
import org.specs2.mutable.Specification

import org.specs2.mutable

    class HelloWorldSpec extends Specification {

     "The 'Hello world' string" should {
      "contain 11 characters" in {
        "Hello world" must have size(11)
      }
      "start with 'Hello'" in {
        "Hello world" must startWith("Hello")
      }
      "end with 'world'" in {
        "Hello world" must endWith("world")
      }
}
}
Guide to write Acceptance
            Specifications
Extend the org.specs2.Specification trait

are functional when extending the default
org.specs2.Specification trait

Must define a method called is that takes a Fragments
object, which is composed of an optional SpecStart , a list of
Fragment objects an options SpecEnd
Creating Acceptance Specifications

package knoldus.Specs2
import org.specs2._

class HelloWorldAcceptanceSpec extends Specification {
 def is =

     "This is a specification to check the 'Hello world' string" ^
      p^
      "The 'Hello world' string should" ^
      "contain 11 characters" ! e1 ^
      "start with 'Hello'" ! e2 ^
      "end with 'world'" ! e3 ^
      end

    def e1 = "Hello world" must have size (11)
    def e2 = "Hello world" must startWith("Hello")
    def e3 = "Hello world" must endWith("world")
}
Acceptance Specifications are
                   functional
The default Specification trait in specs2 is functional: the Result of an example is
always given by the last statement of its body. This example will never fail
because the first expectation is "lost":

 "my example on strings" ! e1            // will never fail!

 def e1 = {
   "hello" must have size(10000)          // because this expectation will not be
returned,...
   "hello" must startWith("hell")
 }

So the correct way of writing the example is:

 "my example on strings" ! e1           // will fail

 def e1 = "hello" must have size(10000) and
               startWith("hell")
Matchers
there are many ways to define expectations in specs2. You
can define expectations with anything that returns a Result:

  Boolean
  Standard result
  Matcher result
  Scalacheck property
  Mock expectation
  DataTable
  Forms
Boolean Result
this is the simplest kind of result you can define for an
expectation but also the least expressive!

Here's an example:

 "This is hopefully true"   ! (1 != 2)

This can be useful for simple expectations but a failure will
give few information on what went wrong:

 "This is hopefully true"   ! (2 != 2) // fails with 'the value is
false',...
Standard Result
Some standard results can be used when you need specific result
meanings:

  success: the example is ok
  failure: there is a non-met expectation
  anError: a non-expected exception occurred
  skipped: the example is skipped possibly at runtime because
some conditions are not met. A more specific message can
  be created with Skipped("my message")
  pending: usually means "not implemented yet", but a specific
message can be created with Pending("my message")

Two additional results are also available to track the progress of
features:

  done: a Success with the message "DONE"
  todo: a Pending with the message "TODO"
Matcher Result
the most common matchers are automatically available when
extending the Specification trait:

1 must beEqualTo(1) the normal way
1 must be_==(1)    with a shorter matcher
1 must_== 1 my favorite!
1 mustEqual 1 if you dislike underscores
1 should_== 1 for should lovers
1 === 1 the ultimate shortcut
1 must be equalTo(1) with a literate style
Iterable Matchers
specs 1.x:

val list = List(1, 2, 3)
list must have size(3)
list must containInOrder(1, 2, 3)

specs2

Using only and inOrder we can state this in one shot:

List(1, 2, 3) must contain(1, 2, 3).only.inOrder
JSON Matchers
specs 1.x:

val list = List(1, 2, 3)
list must have size(3)
list must containInOrder(1, 2, 3)

specs2

Using only and inOrder we can state this in one shot:

List(1, 2, 3) must contain(1, 2, 3).only.inOrder
JSON Matchers
/(value) looks for a value at the root of an Array

"""["name", "Joe" ]""" must /("name")

/(key -> value) looks for a pair at the root of a Map

"""{ "name": "Joe" }""" must /("name" -> "Joe")
"""{ "name": "Joe" }""" must not /("name2" -> "Joe")
Mocking
import org.specs2.mock._
 class MockitoSpec extends Specification { def is =

  "A java list can be mocked"                                    ^
   "You can make it return a stubbed value"                           ! c().stub^
   "You can verify that a method was called"                          ! c().verify^
   "You can verify that a method was not called"                        ! c().verify2^
                                                      end
   case class c() extends Mockito {
     val m = mock[java.util.List[String]] // a concrete class would be mocked with:
mock[new java.util.LinkedList[String]]
     def stub = {
       m.get(0) returns "one"          // stub a method call with a return value
       m.get(0) must_== "one"             // call the method
     }
     def verify = {
       m.get(0) returns "one"          // stub a method call with a return value
       m.get(0)                  // call the method
       there was one(m).get(0)           // verify that the call happened
     }
     def verify2 = there was no(m).get(0) // verify that the call never happened
   }
 }
Forms

Forms are a way to represent domain objects or services, and declare expected values in
a tabular format. Forms can be designed as reusable pieces of specification where
complex forms can be built out of simple ones.


class SpecificationWithForms extends Specification with Forms { def is =

    "The address must be retrieved from the database with the proper street and
number" ^
     Form("Address").
      tr(prop("street", actualStreet(123), "Oxford St")).
      tr(prop("number", actualNumber(123), 20))                          ^
                                                                      end
  }
Running Specification Using Junit
With Junit We can run test as this
import org.junit.runner._
import runner._

@RunWith(classOf[JUnitRunner])
class WithJUnitSpec extends Specification {
  "My spec" should {
    "run in JUnit too" in {
      success
    }
  }
}
Running Specification Using SBT
With Sbt We can run test as this
For console OutPut Add this line in your build.sbt
testOptions in Test += Tests.Argument("console")
And run
test-only classFileName – console


For html output
Add dependencies
"org.pegdown" % "pegdown" % "1.0.2"
testOptions in Test += Tests.Argument("html")
And run
test-only classFileName – html

For html and console output
testOptions in Test += Tests.Argument("html",console)
And run
test-only classFileName – html console
Thanks

More Related Content

What's hot

Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with SpockDmitry Voloshko
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1Chris Huang
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using SpockAnuj Aneja
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2Chris Huang
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeAijaz Ansari
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutDror Helper
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 

What's hot (19)

Clean code
Clean codeClean code
Clean code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Magic methods
Magic methodsMagic methods
Magic methods
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Smarter Testing with Spock
Smarter Testing with SpockSmarter Testing with Spock
Smarter Testing with Spock
 
重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1重構—改善既有程式的設計(chapter 8)part 1
重構—改善既有程式的設計(chapter 8)part 1
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
 
重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2重構—改善既有程式的設計(chapter 8)part 2
重構—改善既有程式的設計(chapter 8)part 2
 
PHP 5 Magic Methods
PHP 5 Magic MethodsPHP 5 Magic Methods
PHP 5 Magic Methods
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCode
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 

Similar to Specs2

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby evalNiranjan Sarade
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
Scala in practice
Scala in practiceScala in practice
Scala in practicepatforna
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in SwiftNetguru
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 

Similar to Specs2 (20)

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby eval
 
Javascript
JavascriptJavascript
Javascript
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Java script
Java scriptJava script
Java script
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Why ruby
Why rubyWhy ruby
Why ruby
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 

Recently uploaded

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 

Recently uploaded (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 

Specs2

  • 1. Specs2 Library for writing Acceptance And Unit Tests Piyush Mishra Software Consultant Knoldus Software LLP
  • 2. Topics Covered What is Specs2 The design principles of specs2 Unit Specifications Acceptance Specifications Matchers Runners
  • 3. What is Specs2 Specs is a DSL in Scala for doing BDD (Behavior-Driven -Development).
  • 4. Design Principles of Specs2 Do not use mutable variables Use a simple structure Control the dependencies (no cycles) Control the scope of implicits
  • 5. Guide to write Unit Specifications Unit specifications Extend the org.specs2.mutable.Specification trait are mutable Use should / in format in creates an Example object containing a Result should creates a group of Example objects
  • 6. Creating Unit Specifications package knoldus.Specs2 import org.specs2.mutable.Specification import org.specs2.mutable class HelloWorldSpec extends Specification { "The 'Hello world' string" should { "contain 11 characters" in { "Hello world" must have size(11) } "start with 'Hello'" in { "Hello world" must startWith("Hello") } "end with 'world'" in { "Hello world" must endWith("world") } } }
  • 7. Guide to write Acceptance Specifications Extend the org.specs2.Specification trait are functional when extending the default org.specs2.Specification trait Must define a method called is that takes a Fragments object, which is composed of an optional SpecStart , a list of Fragment objects an options SpecEnd
  • 8. Creating Acceptance Specifications package knoldus.Specs2 import org.specs2._ class HelloWorldAcceptanceSpec extends Specification { def is = "This is a specification to check the 'Hello world' string" ^ p^ "The 'Hello world' string should" ^ "contain 11 characters" ! e1 ^ "start with 'Hello'" ! e2 ^ "end with 'world'" ! e3 ^ end def e1 = "Hello world" must have size (11) def e2 = "Hello world" must startWith("Hello") def e3 = "Hello world" must endWith("world") }
  • 9. Acceptance Specifications are functional The default Specification trait in specs2 is functional: the Result of an example is always given by the last statement of its body. This example will never fail because the first expectation is "lost": "my example on strings" ! e1 // will never fail! def e1 = { "hello" must have size(10000) // because this expectation will not be returned,... "hello" must startWith("hell") } So the correct way of writing the example is: "my example on strings" ! e1 // will fail def e1 = "hello" must have size(10000) and startWith("hell")
  • 10. Matchers there are many ways to define expectations in specs2. You can define expectations with anything that returns a Result: Boolean Standard result Matcher result Scalacheck property Mock expectation DataTable Forms
  • 11. Boolean Result this is the simplest kind of result you can define for an expectation but also the least expressive! Here's an example: "This is hopefully true" ! (1 != 2) This can be useful for simple expectations but a failure will give few information on what went wrong: "This is hopefully true" ! (2 != 2) // fails with 'the value is false',...
  • 12. Standard Result Some standard results can be used when you need specific result meanings: success: the example is ok failure: there is a non-met expectation anError: a non-expected exception occurred skipped: the example is skipped possibly at runtime because some conditions are not met. A more specific message can be created with Skipped("my message") pending: usually means "not implemented yet", but a specific message can be created with Pending("my message") Two additional results are also available to track the progress of features: done: a Success with the message "DONE" todo: a Pending with the message "TODO"
  • 13. Matcher Result the most common matchers are automatically available when extending the Specification trait: 1 must beEqualTo(1) the normal way 1 must be_==(1) with a shorter matcher 1 must_== 1 my favorite! 1 mustEqual 1 if you dislike underscores 1 should_== 1 for should lovers 1 === 1 the ultimate shortcut 1 must be equalTo(1) with a literate style
  • 14. Iterable Matchers specs 1.x: val list = List(1, 2, 3) list must have size(3) list must containInOrder(1, 2, 3) specs2 Using only and inOrder we can state this in one shot: List(1, 2, 3) must contain(1, 2, 3).only.inOrder
  • 15. JSON Matchers specs 1.x: val list = List(1, 2, 3) list must have size(3) list must containInOrder(1, 2, 3) specs2 Using only and inOrder we can state this in one shot: List(1, 2, 3) must contain(1, 2, 3).only.inOrder
  • 16. JSON Matchers /(value) looks for a value at the root of an Array """["name", "Joe" ]""" must /("name") /(key -> value) looks for a pair at the root of a Map """{ "name": "Joe" }""" must /("name" -> "Joe") """{ "name": "Joe" }""" must not /("name2" -> "Joe")
  • 17. Mocking import org.specs2.mock._ class MockitoSpec extends Specification { def is = "A java list can be mocked" ^ "You can make it return a stubbed value" ! c().stub^ "You can verify that a method was called" ! c().verify^ "You can verify that a method was not called" ! c().verify2^ end case class c() extends Mockito { val m = mock[java.util.List[String]] // a concrete class would be mocked with: mock[new java.util.LinkedList[String]] def stub = { m.get(0) returns "one" // stub a method call with a return value m.get(0) must_== "one" // call the method } def verify = { m.get(0) returns "one" // stub a method call with a return value m.get(0) // call the method there was one(m).get(0) // verify that the call happened } def verify2 = there was no(m).get(0) // verify that the call never happened } }
  • 18. Forms Forms are a way to represent domain objects or services, and declare expected values in a tabular format. Forms can be designed as reusable pieces of specification where complex forms can be built out of simple ones. class SpecificationWithForms extends Specification with Forms { def is = "The address must be retrieved from the database with the proper street and number" ^ Form("Address"). tr(prop("street", actualStreet(123), "Oxford St")). tr(prop("number", actualNumber(123), 20)) ^ end }
  • 19. Running Specification Using Junit With Junit We can run test as this import org.junit.runner._ import runner._ @RunWith(classOf[JUnitRunner]) class WithJUnitSpec extends Specification { "My spec" should { "run in JUnit too" in { success } } }
  • 20. Running Specification Using SBT With Sbt We can run test as this For console OutPut Add this line in your build.sbt testOptions in Test += Tests.Argument("console") And run test-only classFileName – console For html output Add dependencies "org.pegdown" % "pegdown" % "1.0.2" testOptions in Test += Tests.Argument("html") And run test-only classFileName – html For html and console output testOptions in Test += Tests.Argument("html",console) And run test-only classFileName – html console