Published on

This is a presentaion on specs2 for writing Unit and Acceptance Tess

Published in: Technology, Business
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Specs2Library for writing Acceptance And Unit Tests Piyush Mishra Software Consultant Knoldus Software LLP
  2. 2. Topics CoveredWhat is Specs2The design principles of specs2Unit SpecificationsAcceptance SpecificationsMatchersRunners
  3. 3. What is Specs2Specs is a DSL in Scala for doing BDD(Behavior-Driven -Development).
  4. 4. Design Principles of Specs2Do not use mutable variablesUse a simple structureControl the dependencies (no cycles)Control the scope of implicits
  5. 5. Guide to write Unit SpecificationsUnit specificationsExtend the org.specs2.mutable.Specification traitare mutable Use should / in format in creates an Example objectcontaining a Result should creates a group of Exampleobjects
  6. 6. Creating Unit Specificationspackage knoldus.Specs2import org.specs2.mutable.Specificationimport 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. 7. Guide to write Acceptance SpecificationsExtend the org.specs2.Specification traitare functional when extending the defaultorg.specs2.Specification traitMust define a method called is that takes a Fragmentsobject, which is composed of an optional SpecStart , a list ofFragment objects an options SpecEnd
  8. 8. Creating Acceptance Specificationspackage knoldus.Specs2import 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. 9. Acceptance Specifications are functionalThe default Specification trait in specs2 is functional: the Result of an example isalways given by the last statement of its body. This example will never failbecause 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 bereturned,... "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. 10. Matchersthere are many ways to define expectations in specs2. Youcan define expectations with anything that returns a Result: Boolean Standard result Matcher result Scalacheck property Mock expectation DataTable Forms
  11. 11. Boolean Resultthis is the simplest kind of result you can define for anexpectation but also the least expressive!Heres an example: "This is hopefully true" ! (1 != 2)This can be useful for simple expectations but a failure willgive few information on what went wrong: "This is hopefully true" ! (2 != 2) // fails with the value isfalse,...
  12. 12. Standard ResultSome standard results can be used when you need specific resultmeanings: 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 becausesome conditions are not met. A more specific message can be created with Skipped("my message") pending: usually means "not implemented yet", but a specificmessage can be created with Pending("my message")Two additional results are also available to track the progress offeatures: done: a Success with the message "DONE" todo: a Pending with the message "TODO"
  13. 13. Matcher Resultthe most common matchers are automatically available whenextending the Specification trait:1 must beEqualTo(1) the normal way1 must be_==(1) with a shorter matcher1 must_== 1 my favorite!1 mustEqual 1 if you dislike underscores1 should_== 1 for should lovers1 === 1 the ultimate shortcut1 must be equalTo(1) with a literate style
  14. 14. Iterable Matchersspecs 1.x:val list = List(1, 2, 3)list must have size(3)list must containInOrder(1, 2, 3)specs2Using only and inOrder we can state this in one shot:List(1, 2, 3) must contain(1, 2, 3).only.inOrder
  15. 15. JSON Matchersspecs 1.x:val list = List(1, 2, 3)list must have size(3)list must containInOrder(1, 2, 3)specs2Using only and inOrder we can state this in one shot:List(1, 2, 3) must contain(1, 2, 3).only.inOrder
  16. 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. 17. Mockingimport 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. 18. FormsForms are a way to represent domain objects or services, and declare expected values ina tabular format. Forms can be designed as reusable pieces of specification wherecomplex 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 andnumber" ^ Form("Address"). tr(prop("street", actualStreet(123), "Oxford St")). tr(prop("number", actualNumber(123), 20)) ^ end }
  19. 19. Running Specification Using JunitWith Junit We can run test as thisimport org.junit.runner._import runner._@RunWith(classOf[JUnitRunner])class WithJUnitSpec extends Specification { "My spec" should { "run in JUnit too" in { success } }}
  20. 20. Running Specification Using SBTWith Sbt We can run test as thisFor console OutPut Add this line in your build.sbttestOptions in Test += Tests.Argument("console")And runtest-only classFileName – consoleFor html outputAdd dependencies"org.pegdown" % "pegdown" % "1.0.2"testOptions in Test += Tests.Argument("html")And runtest-only classFileName – htmlFor html and console outputtestOptions in Test += Tests.Argument("html",console)And runtest-only classFileName – html console
  21. 21. Thanks
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.