Spock : A new era of functional testing

Lacks of Testing framework + Mocking framework == Spock

Spock is a testing framework that in great extent utilizes Groovy’s syntax making your tests comprehensible and easy on the eyes which means that runs on the Java Virtual Machine (JVM) and let you test code written in any of the languages the JVM supports.

Why you might use Spock?

Tests created in Spock tend to be more informative, better arranged and easier to understand for others.

  • Easy to learn. It really is, even if you don’t know Groovy.
  • Very Good syntactic sugar for mocking, stubbing and spying these operations can be accomplished by really simple code, hence they do not veil test’s logic.
  • Detailed information. This alone should make you leave behind any other frameworks.
  • Beautiful language. I’ve tried other BDD frameworks, but Spock has created a better and more expressive domain-specific language  (DSL).

Minimal Groovy knowledge you need for Spock

Groovy is a language that it’s compiled to bytecode that is executed by the JVM, and it’s very similar to Java, but with features comparable to Ruby, Python, or Javascript.

For example, everything is treated as an object and semicolons are optional:

int x = 4 // Valid  
x.getClass() // java.lang.Integer 

Simple test in Spock

def "should return 2 from first element of list"() {  
given:  List list = new ArrayList<>()  
when:  list.add(1)  
then:  2 == list.get(0) 
} 

Above test should fail (putting 1 into list and then expect 2 to be retrieved). Spock will display a clear and easy to understand error message, explaining precisely what went wrong.

Condition not satisfied: 2 == list.get(0)   
|         |         |      |  [1] 1   false 

Spock Blocks

Blocks divide a method into sections. They start with a label and extend either to the beginning of the next block or the end of the method. We already use the given, when and then, but there’re six blocks actually:

  • setup: (or its alias, given:)
  • when:
  • then:
  • expect:
  • cleanup:
  • where:

Please take notice how clear a declaration of a test in Spock is. Any one do not have to follow the standard naming convention for methods and instead can declare the name of a test between two apostrophes. Thanks to that creating long but descriptive names for tests seems more natural and as well allows others to better understand what the purpose of a test it.
As mentioned before tests in Spock are arranged in a way resembling BDD tests. Each test can be divided into three sections.

Setup (Given section)

First of all we want to specify the context within which we would like to test a functionality. This is where you want to specify the parameters of your system/component that affect a functionality that is under the test. This section tends to get really big for all Spock rookies, but ultimately you will learn how to make it more concise and descriptive.

When section

This is where we can specify what we want to test. In other words what interaction with tested object/component we would like to study.

Then section

Now, here we verify what the result of the action performed in when section was. I.e. what was returned by the method (black box test) or what interactions have taken place in mocks and spies used inside tested function (white box test).

def "should return false if user does not have role required for  viewing page"() {
given:  // context pageRequiresRole 
Role.ADMIN  userHasRole Role.USER 
when:  // some action is performed  
boolean authorized = authorizationService.isUserAuthorizedForPage(user, page)              
then:  // expect specific result  
authorized == false
} 

Alternative sections

In Spock documentation you will be able to find some alternatives for the above sections, e.g.  expect,cleanup,where.

Expect

The expect: block is the same as then:, it can only contain conditions or variable definitions, but it doesn’t require a then: block:

def "should calculate power of number 2"() {
  expect:  Math.pow(2) == 4 
} 

Cleanup

The optional cleanup: block is used to free resources and is run even if the code before the block has thrown an exception. It’s usually the last block in the method, but it may only be followed by a where: block:

given:  def file = new File('/temp/1.txt')  //...  
cleanup:  file.close()

Where

def 'data-driven test'() { 
expect:  x + y == z  
where:   x  | y  | z  
         3  | 4  | 7  
         19 | 23 | 42  
         71 | 12 | 83  
}

Spock will run as many tests as rows in the where block. In the example, Spock will execute three tests, and the vars x, y, and z will be initialized to the following values:

Fixture Methods

Fixture methods are responsible for setting up and cleaning up the environment in which feature methods are run. Usually it’s a good idea to use a fresh fixture for every feature method, which is what the setup() and cleanup()methods are for.

def setupSpec() {}    // runs once -  before the first feature method
def setup() {}        // runs before every feature method
def cleanup() {}      // runs after every feature method
def cleanupSpec() {}  // runs once -  after the last feature method

Stubbing method calls

In Spock we can distinguish three classes that are able to override a behaviour of some other class or interface: Stubs, Mocks and Spies. In this section we will focus on Stubs as unlike two others imitating other classes is their only responsibility. Nevertheless the syntax for imitating behaviour is the same for all three classes, hence everything shown here will work the same way with Mocks and Spies.

Creating Stub

In order to create a Stub one has to call the Stub() method inside a Spock test.

def "creating example stubs"() {  
given:  List list = Stub(List)  
        List list2 = Stub() 
        // preffered way  
        def list3 = Stub(List)  
}

Specifying the return value

Basically what we want to do with Stubs is to define what should happen when a particular method of stubbed class is invoked. In order to specify what value should be returned by stubbed method we use right shift operator >> and then specify the return value.

def "should return Role.USER when asked for role"() {  
given:  List list = Stub()  
list.size() >> 3  
expect:  // let's see if this works  
list.size() == 3 
}

Specifying side effects

If we want to specify some side effect as the result of method invocation we put a closure after right shift operator. Thus every time the method be will invoked during the execution of the test the code within the closure will be executed.

def "specifying side effects"() {  
given:  List list = Stub()  
list.size() >> { println "Size method has been invoked" } 
}

Throwing an exception as the result of method invocation

We can use the above side effect technique to throw an exception when a method is invoked.

def "specifying that exception should be thrown"() {  
given:  List list = Stub()  
list.size() >> { throw new IllegalStateException() } 
} 

Checking interactions on Mock/Spies

Sometimes you do not really need to specify the behaviour of a dummy object you create for your unit test. Rather than that you are interested in checking whether a particular method from some interface has been invoked during the execution of your programme. To achieve that you can use Mock or Spy. In this section we will discuss the former of two, but everything presented here can be used with Spies as well.

Using mocks has one drawback though that we have to be aware of. When we check interactions, rather than verifying a contract of some interface, we are testing its particular implementation. Nevertheless, tests checking interactions on components can be really handy in case we carry out a large refactoring and e.g. we want to make sure that as a result we will not loose a crucial validation before inserting data to database.

Creating Mock

In order to create a Mock one has to call Mock() method inside a Spock test.

def "creating example stubs"() {  
given:  List list = Mock(List)  
List list2 = Mock() 
// preffered way  
def list3 = Mock(List)  
}

Matching invocations in mocks

The same means that were used to match invocation for stubbing can be used with mocks.

def "should fail due to wrong user"() { 
given:  UserService userService = Mock()  
User user = new User(name: 'Mefisto')  
when:  userService.save(user)  
then:  1 * userService.save({ User u -> u.name == 'Lucas' }) } 
Too few invocations for: 1 * userService.save({ User u -> u.name == 'Lucas' }) (0 invocations) 
Unmatched invocations (ordered by similarity): 1 * userService.save(ExampleSpockTest$User(Mefisto)) 

There are lots of other features present in Spock, just explore them.

Groovy Tricks

capitalize() method :

The capitalize() method available in String class. This will capitalize the first letter of the String.
For example:

def someString = 'mrAshu'.capitalize() 
println someString
Output : MrAshu 

def someString = 'string'.capitalize() 
println someString 
Output : String 

uncapitalize() method :

Since Groovy 2.4.8 we can use the uncapitalize method on CharSequence objects. The capitalize method was already available for a long time, but now we have the opposite as well.
In the following example we see that the uncapitalize method only replaces the first letter of a String value to lower case:

def someString = 'MrAshutosh'.uncapitalize() 
println someString 
Output : mrAshutosh  

def someString = 'String'.uncapitalize() 
println someString 
Output : string 

Truncate And Round BigDecimal Values :

Groovy 2.5.0 adds round and truncate methods to the BigDecimal class. These methods were already available on Double and Float classes. The methods can take an argument to denote the number of decimals the rounding or truncating must be applied to.
In the following example we see the methods with and without arguments:

def bigDecimal = 87.576135 
// Groovy uses BigDecimal for decimal numbers by default. 
assert bigDecimal.class.name == 'java.math.BigDecimal' 

// round method takes rounded values.  
assert bigDecimal.round() == 87 
assert bigDecimal.round(2) == 87.58 

// trunc method just truncate the values. 
assert bigDecimal.trunc() == 87 
assert bigDecimal.trunc(2) == 87.57 

Use Optional In Conditional Context :

In Groovy 2.5.0 we can use a Java 8 Optional object in a conditional context.
When an Optional object has a value the value is coerced to true and when empty the value is false.

assert !Optional.empty() 
assert !Optional.ofNullable(null) 
assert Optional.of('Groovy fantastics!') 

Swaps the List elements. :

Provide the two index values of the elements we want to swap and Groovy swaps the elements.

def saying = ['Groovy', 'is', 'great']  
def languageSays = saying.swap(2, 1).swap(0, 1)  
assert languageSays.join(' ') == 'great Groovy is' 

Text Translation or replacement :

With tr()  method we can do translations in String values. We define a source set of characters that need to be replaced by a replacement set of characters.
Also use a regular expression style (not a real regular expression) to define a range of characters.

// Source set and replacement set are equal size. 
def someString = 'Groovy is Best'.tr('GoBs', '5028') 
println someString 
Output : 5r00vy i8 2e8t 

// Regular expression style range 
def someString = 'mrashu'.tr('a-u', 'A-U') 
println someString 
Output : MRASHU 

// Replacement set is smaller than source set. 
def someString = 'Groovy'.tr('ovy', '8') 
println someString 
Output : Gr888 

New Implementation of Pop/Push Methods

After Groovy 2.5.0 the implementations for pop() and push() methods has changed.
They now work on the first item in a List instead of the last.
pop() – Remove the first item of a List.
push() – Add item to beginning of a List.

def list = ['Groovy', 'is', 'fun!']
/** pop */
list.pop() == 'Groovy'
println list
Output : [is, fun!]
/** push */
list.push 'Spock' 
println list
Output : [Spock, is, fun!]

Spock Tricks

Reuse Variables In Data Providers :

Writing a parameterized specification in Spock very is easy.
We need to add the where: block and use data providers to specify different values.
For each set of values from the data providers our specifications is run, so we can test for example very effectively multiple input arguments for a method and the expected outcome.
A data provider can be anything that implements the Iterable interface.
Spock also adds support for a data table.
In the data table we define columns for each variable and in the rows values for each variable.

Since Spock 1.1 we can reuse the value of the variables inside the data provider or data table.
The value of the variable can only be reused in variables that are defined after the variable we want to reuse is defined.
In the following example we have two feature methods, one uses a data provider and one a data table.
The variable sentence is defined after the variable search,
so we can use the search variable value in the definition of the sentence variable.

package spockTricks 

import spock.lang.Specification 
import spock.lang.Unroll 

class CountOccurrencesSpec extends Specification { 
@Unroll('#sentence should have #count occurrences of #search (using data table)') 

void 'count occurrences of text using data table'() {
expect: sentence.count(search) == count 

where: 
search | sentence || count 
'ABC'  | "A simple $search" || 1 
'Spock' | "Don't confuse $search framework, with the other $search"|| 2 
 } 

@Unroll('#sentence should have #count occurrences of #search (using data provider)') 
void 'count occurrences of text using data provider'() { 
expect: sentence.count(search) == count 
where: 
search << ['ABC', 'Spock'] 
sentence << ["A simple $search", "Don't confuse $search framework, with the other $search"] 
count << [1, 2] 
 }
} 

Scalable Load testing of web Services on Cloud using Soap UI

Scalability is the capability of a system, to handle a growing amount of load, or its potential to be enlarged in order to accommodate that growth.

Before going to the production an application developer needs to do performance/load testing of any web application/ web services. Always we want cost effective solution for this purpose.
For this is motive you must have load testing framework in your toolbox.

MY Tool kit- In my  tool kit I have open source Soap-UI 5.2.1, elastic search, mysql, jenkins 2.0 and groovy to do load testing for Soap/Rest service on AWS cloud.

Why load testing is requires ?

Perform a load testing for SOAP and Rest services for following reason:

1. Get the average response time and test per second of web service under certain load.
2. Ensure the maximum capacity (number of requests per second) of the web server based on the current hardware infrastructure.
3. Get the CPU, Memory, Disk IO and Network usage for web server under certain load.
4. Exposes potential bottlenecks in your system and generate a load test result report for analysis.

Achieve this by using Soap-UI oppen source addition-

SoapUI  is great tool for the functional as well as load testing. It generate the request and response using data contract provided through WSDL or WADL. Soap-UI comes with the capability of groovy script implicitly, it helps to manipulate the request, response as well as to get and save the test data to/from external sources.

Soap UI has user friendly GUI which help a lot to create test suite, test cases and test step. SoapUI also support the property transfer test steps which helps to parse the response from previous request and set the properties at project, test suite, test case level. Properties are key value pair which can be accessed inside the request using expression language e.g ${#Project#PropertyName}. More details about SoapUI.

According to me groovy script is the heart of SoapUI. We can use groovy test step to parse the response and apply some use case logic and set the properties for next request or store the responses in external sources which can be used for further processing.

At the time of load testing I was interested in numbers like avg response time (avg) and test per seconds (TPS) and number of requests depending on load test strategy. SoapUI community edition provides Basic CSV file reporting. We integrated elastic search for reporting with Soap UI for load test results. For more about performance matrix.

The distributed SoapUI load test results is dumped into the Elastic Search and the reports are visualized using the Kibana web user interface.

When we through load on system we need to get the some metrics like CPU, Memory, Disk IO, Network utilization. We achieve it bu using PerfMon a Jmeter Server Agent and custom TCP client for it. The tcp perfmon client also inserting the result into elastic search. It will be very helpful to analyze the load test stats with performance metrics.

loadtest

The above mention setup work well from single instance but load testing need to scale on multiple instance to generate more load on server. In that case the current setup works as master node having Elastic search, mysql, PerfMon Tcp client, SoapUI load test runner and Jenkins for managing master/slave node. The Jenkins master will distribute the SoapUI load test runner job on SSH Client slave machines in a network. The slave node run the SoapUILoadTestRunner Job and publish the load test result to elastic search hosted on the master node. The scalability is achieved through adding n-numbers of slave node on the Cloud. These slave nodes are ubuntu based EC2 intances.

loadtestslave

This is cost effective solution for load testing using open source SoapUI against the paying huge license cost of SoapUI Pro and LoadUI Pro which help us to get more or less same result.

 

SoapUI push and pull data from database

Some time there is a need that how can maintain data in the data driven testing.
Here I am going to describe how to read and write data using simple groovy script and the MySQL .
SoapUI- For the testing of APIs SoapUI is a open source tool.
Groovy-  Is a rich language and inbuilt supported by SoapUI.
MySQL – MySQL is also freely available database.

Step 1 – MySQL setup

  • Download latest version of  MySQL from here.
  • Extract downloaded version of MySQL.

Example – Extract mysql-5.5.41-winx64.zip

  • Then go to mysql-5.5.41-winx64\bin and open cmd  by pressing shift + Right click.
  • In the cmd type mysqld.
  • MySQL is ready to use.

Step 2 – SQLYog  setup for accessing MySQL DB

Download latest version of SQLYog community addition from here.
Open SQLYog (If not installed then install first).
Click on create new connection.
Fill the required settings like Host address, username, port etc.

sqlyog

Click on connect. If all the settings are proper then connection should established.

Step 3 – Connection with SoapUI

  • Download latest version of  MySQL connector jar file from here.
  • Go to soap installation folder.

Example – C:\Program Files\SmartBear\SoapUI-5.1.3\bin\ext

  • Copy mysql-connector-java-givenversion.jar and paste there.
  • Now SoapUI is connected with My SQL.

Insert service response in to MySQL (Write data)

Let be considered there is a TestRequest and in the response of given request suppose I want to extract four fields .

  1. userId
  2. userName
  3. zip
  4. email

So I want to insert these fields with corresponding data in MySQL DB.

Add groovy script step under the given request step and write following script.

import groovy.sql.Sql
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver("com.mysql.jdbc.Driver") 
try { 
def response = context.expand('${TestStep#Response}')   
def xml = new XmlSlurper().parseText(response)   
log.info(xml)    
def userId = xml.Body.Response.CreateUserResult.User.Id;   
def userName = xml.Body.Response.CreateUserResult.User.UserName;   
def zip = xml.Body.Response.CreateUserResult.User.Profile.Address.Zip;   
def email = xml.Body.CreateUserResult.User.Profile.Contact.email.Value;   log.info("url value: " + new Integer( userId.toInteger()) + " " + userName.toString()+ " " + zip.toString()+ " " + email.toString() );   def sql = Sql.newInstance("jdbc:mysql://localhost/test", "root",  "", "com.mysql.jdbc.Driver")   
sql.execute( "insert into tablename (UserId, UserName,Zip,Email)  values ( ?, ?, ? ,? )",
[userId.toInteger(),
userName.toString(), 
zip.toString(),
email.toString(), 
addressLine1.toString()]
)    
sql.close() 
}
catch(Exception e)  {
  log.info(e);  
} 

Read data from MySQL 

Consider in my next request I want to retrieve inserted data.

import groovy.sql.Sql 
com.eviware.soapui. support.GroovyUtils.registerJdbcDriver("com.mysql.jdbc.Driver")  
// call the loadTestContext and store it in a local variable  
def ltContext = context.LoadTestContext   
try{    
// synchronize the part of code in which you are accessing the variable.   
synchronized(ltContext){      
if(ltContext.sql==null){
log.info(ltContext.sql)   
ltContext.sql = Sql.newInstance("jdbc:mysql://localhost/test","root",  "", "com.mysql.jdbc.Driver")   } 
//serialNo is the code that I want to be synchronized for the threads. 
//check for Null   
if(ltContext.id == null)  {   ltContext.count = 0  ltContext.sql.eachRow("select count(id) from tablename") {
 row ->  ltContext.count = row[0]  
}   
def frow = ltContext.sql.firstRow("select * from tablename ORDER BY id" + " limit 1")    
ltContext.id = frow.id;   
ltContext.resetId = frow.id;   
ltContext.count = ltContext.count + ltContext.id  
def currentTestCase = context.testCase  currentTestCase.setPropertyValue("UserId", frow.UserId.toString())    }  
else  { if(ltContext.id < ltContext.count )  { ltContext.id = ltContext.id + 1;    
def frow = sql.firstRow("select * from vexiereuser where id ="  +ltContext.id +" limit 1")    
ltContext.id = frow.id;   
def currentTestCase = context.testCase.currentTestCase.setPropertyValue("UserId", frow.UserId.toString()) } else {  
ltContext.id = ltContext.resetId;  
def currentTestCase = context.testCase  currentTestCase.setPropertyValue("UserId",ltContext.id.toString())  
}   
}    
sql.close()   
// In load test don't close the connection.   
}  
log.info(ltContext.id)  
log.info(ltContext.count)    
}catch(Exception e){
  log.info(e); 
} 

So this is the simple example of read and write data in SoapUI from MySQl. Reading of bulk data is very useful in the load testing.

Overview of Performance Testing for Web Services

When I started performance testing, I learnt about and was trained with the term “load testing”. Sometimes people referred / used the term “stress testing” and  it’s the same thing, not to worry. Today people still use mainly those two terms.

The focus is definitely still on load testing and there’s nothing wrong with that. The end goal should always be a system that performs well under load. The way we get there is what matters.

I’ll try to give a short overview to Performance Testing here and what it means for Web Service Testing.

Performance Testing-

Artificially generating or simulating load and evaluating how your system handles it.

This means it doesn’t necessary have to be how a system performs under high load, it can also be how it performs under base load or expected load.

Types of  Performance Testing-

There are a multiple definitions of performance testing, please understand that we know that this is only one way to define performance testing.

Baseline Testing

Objective: Find metrics for system performance under normal load.

This is purely technically exactly what Performance Testing is, but we feel it’s important to establish as a separate task. Baseline tests form a very important part of the performance test methodology . If this done properly, 85% of performance problems can be identified and solved when proper baseline tests are done.

Baseline Testing examines how a system performs under expected or normal load and creates a baseline against which the other types of tests can be related.

Load Testing

Objective:Find metrics for system performance under high load.

Load Testing includes increasing the Load and see how the system behaves under higher load. During Load Tests you can monitor response times, throughput, server condition and much more. The goal of Load Testing is not to break the target environment though.
So we test system with multiple users to determine performance under load. The number of users is usually specified by the performance test requirements.

Stress Testing

Objective: Determine the system breaking point or threshold. How the system breaks and recovers should also be monitored.

The goal of Stress Test is exactly that; to find the volume of load where the system actually breaks or is close to breaking.
It means load the system to its break-point.

Soak / Endurance Testing

Objective: Testing a system under load for an extended period of time to establish stability and behavior under sustained use.

In order to find system instabilities that occur over time, we need to conduct tests that run over a long period. That is what Soak Testing is for; run Load Tests or even Baseline Tests over a long period of time and see how the target environment handles system resources and that we see no unwanted behavior as a result of the time as a factor.
The most common defect found by Soak Testing is memory leaks.
The most common scenario for Soak Testing is turning on a number of tests when you leave work on a Friday and let it run over the weekend.

Scalability / Volume Testing

Objective: Testing a system with a certain amount of data. Usually includes high data and throughput volumes.

Scalability Testing is very much like Load Testing, but instead of increasing the number of requests, we instead increase the size or the complexity of the requests sent. This involves for example sending large requests, large attachments, or deeply nestled requests.

More about scalable load testing.

Collect server stats like cpu, memory and network

This is a solution to get server stats like cpu, memory and network usage while executing test on the server.

The server stats and soapui load test result is sent to elastic search using tcp and elastic search plugin.

Pre requisite:
1. Project must be setup
2. http://jmeter-plugins.org/wiki/PerfMonAgent/ need to install a server agent.
3. JRE 1.7 and above
4. ELK setup is required.

Following steps need to perform:

Step 1: Go to project directory …/soapui-load-test

Step 2: Start logstash agent with following configuration

logstash agent -f server.conf

#server.conf
input {
 tcp {
 port => 9890
 }
}
output {
 elasticsearch {
 cluster => "loadtestelasticsearch"
 host => "localhost"
 }
}

Step 3: Start Performance client for monitoring server stats and also start tcp listener to stop monitoring.

mvn exec:java -Dexec.mainClass="com.tavisca.vexiere.perfmon.PerfMonClient" -Dexec.args="-t ip1:port1#ip2:port2 
-p tempPort -lg ip4:port4" -pl perf-mon-start,logstashforwarder

"t"  : Give the IP address and port no for target server agent. i.e ip1:port1#ip2:port2 etc
"p"  : Give the port no for perf mon server i.e. int default is 12999
"lg" : Give the IP address and port no for logstash forwarder. i.e ip1:port1

Step 4:  Start soapui load test runner.

mvn exec:java -Dexec.mainClass="com.tavisca.vexiere.loadtest.VexiereLoadTestMain" -Dexec.args="-lg ip4:port4" -pl soap-ui-load-test-runner,logstashforwarder

"tc"    : Give the thread count default is 5.
"limit" : Give the limit for number of request default is 100.

Step 5: Stop the monitoring of the yours project server stats after completing the load test:

mvn exec:java -Dexec.mainClass="com.tavisca.perfmon.client.PerfMonSutdownServerClient" -Dexec.args="-q tempPort" -pl per-mon-shutdown

"q" : "Give the port no for perf mon server i.e. int default is 12999

Note: To execute it on jenkins remove the mvn part from all commands.

Use kibana  to visualize the load test result.

Overview of Performance Testing for Web Services

BDD with Cucumber-JVM

Express the behavior of system

Cucumber-jvm is an open source BDD tool that lets user express the behavior of system under test in plain language like English, French, German etc. It is a great way to have an executable documentation of your system.

Required Maven Dependencies

Picture1


info.cukes
cucumber-picocontainer
${cucumber.version}


info.cukes
cucumber-junit
${cucumber.version}

Gherkin Keywords

Gherkin is the language that Cucumber understands.Gherkin is primarily used to write structured tests which can later be used as project documentation. The property of being structured gives us the ability to automate them.

Scenarios – Given When Then

We can define scenarios in given, when and then format.

Example-

Given a customer added one Item in shopping cart.
When the customer adds same Item in shopping cart.
Then the customer should be warned that same item is already in yours shopping cart.

Writing Scenario’s in Cucumber

• Scenarios are organized together into features.
• Each feature is represented as a plain text file.
• Feature files must have the “.feature” extension.
• Each feature can contain many scenarios.

Step Definitions

• A single Method representing a Step from a Feature file.
• The Method is annotated with information about the step it represents.
• Cucumber generates “Code Snippet’s” for Step Definition it can’t find.

Step Annotations

import cucumber.annotation.en.*;

Each Gherkin step keyword has a Annotation.


@When("^we want to stop traffic$")
public void methodName() { 
   ..........
}

Passing and Failing

Each step has it own result state.
– Passed
– Pending
– Skipped
– Failed
Individual step result state combined determine the Scenarios success or failure.
Steps can be failed on exceptions  or JUnit Assertion failures.

Regex Lesson

Cucumber uses Regular Expressions to match steps to definitions.

@When("^we want to stop traffic$")

^   Matches the starting position

$   Matches the ending position

Capturing Arguments

The pair of brackets is a capture group
Everything captured is passed to method parameter
Cucumber will automatically convert to the method parameter type
Equal number of method parameters and capture groups

@Given("^an owner with a pet called \"Browny\"$")

public void an_owner_with_a_pet_called() {
......
}
@Given("^an owner with a pet called \"([^\"]*)\"$")

public void an_owner_with_a_pet_called(String name) {
......
}

Type Conversion

If the captured string is not in the correct format for type conversion an error will be thrown.
Use regular expressions to capture the correct format string for the type.
Note: Escape regular expression characters with backslash.

Typical Capture Groups

  • (.+) Good for capturing strings and dates
  • \”([^\”]*)\” Captures a string within Double quotes
  • (\\d) Capture decimal numbers only
  • (\\d+\\.\\d+) Capture floating point numbers
  • (true|false) Captures a Boolean value

Date Formats

@Given ("^today is (.+)$")

public void today_is(Date date) {
......
}

Dates are recognized if it’s a format from the DateFormat class.

  • SHORT is completely numeric, such as 12.13.52 or 3:30pm.
  • MEDIUM is longer, such as Jan 12, 1952.
  • LONG is longer, such as January 12, 1952 or 3:30:32pm.
  • FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

Example-


import cucumber.DateFormat;

@Given ("^today is (.+)$")

public void today_is(@DateFormat ("yyyy-MM-dd") Date date) {
......
}

Tags

The tags can be used when specifying what tests to run through any of the running mechanism.
So tag is uses for grouping Scenarios together

  • Identify slow running test that shouldn’t be run frequently.
  • Identify tests that require a particular library or server.

So we can add tags in our feature file-

@feature
Feature: TestSample

 @one @three
 Scenario: Example
 Given .....
 When ......
 Then ......

 @one
 Scenario: Example Two
 Given .....
 When ......
 Then ......

 @three
 Scenario: Example Three
 Given .....
 When ......
 Then ......

 @ignore
 Scenario: Example Four
 Given .....
 When ......
 Then ......

For the better understanding of tags and there execution please view @CucumberOptions.

Some Useful Liks –
Official website: cukes.info
https://github.com/cucumber/cucumber/wiki
http://behaviour-driven.org/
github.com/cucumber/cucumber-jvm
http://www.engineyard.com/blog/
http://groups.google.com/group/cukes

JUnit Runner with @CucumberOptions

When we talk about Cucumber JVM for Behavior Driven development, we often talk about “@CucumberOptions”.

JUnit Runner

Create one empty class with the @RunWith(Cucumber.class) annotation.
Executing this class as any JUnit test class will run all features found on the classpath in the same package as this class.Name of the class could be anything like RunYoursTest.java

import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)

public class RunYoursTest 
{
// This class will be empty 
}

JUnit Runner with @CucumberOptions

@CucumberOptions annotation provides the same options as the cucumber jvm command line. for example: we can specify the path to feature files, path to step definitions, if we want to run the execution in dry mode or not etc.This is very helpful and importance if we are using IDE such eclipse only to execute our project.

Lets take above mentioned RunWith(Cucumber.class) annotation. The options to be used are defined with the @CucumberOptions.

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(//your cucumber options goes here)

public class RunYoursTest 
{
// This class will be empty 
}

There are different type of options present under @CucumberOptions. Lets look at each option one by one to understand it better.

Plugin: plugin Option is used to specify different formatting options for the output reports. Various options that can be used as for-matters are:
Note – Format option is deprecated . Use Plugin in place of that.

A- Pretty: Prints the Gherkin source with additional colors and stack traces for errors.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"}, strict = false)

public class RunYoursTest 
{
 // This class will be empty 
}

B- HTML: This will generate a HTML report at the location mentioned in the for-matter itself.

@RunWith(Cucumber.class)
@CucumberOptions(plugin ={"pretty" , "html:Folder_Name"}) 

public class RunYoursTest 
{
 // This class will be empty 
}

C- JSON: This report contains all the information from the gherkin source in JSON Format. This report is meant to be post-processed into another visual format by 3rd party tools such as Cucumber Jenkins.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty" ,
                            "json:Folder_Name/cucumber.json"}) 
public class RunYoursTest 
{
 // This class will be empty 
}

D- JUnit: This report generates XML files just like Apache Ant’s JUnit report task. This XML format is understood by most Continuous Integration servers, who will use it to generate visual reports.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty" ,
                           "junit:Folder_Name/cucumber.xml"}) 
public class RunYoursTest 
{
 // This class will be empty 
}

We can also use these option together.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty" ,"html:Folder_Name" ,
                           "json:Folder_Name/cucumber.json" ,
                           "junit:Folder_Name/cucumber.xml"}) 

public class RunYoursTest 
{
 // This class will be empty 
}

DryRun: This option can either set as true or false (default value is false). If it is set as true, it means that Cucumber will only checks that every Step mentioned in the Feature File have corresponding code written in Step Definition file or not. So in case any of the function is missed in the Step Definition for any Step in Feature File, it will give us the message. So If you writing scenarios first and then implementing step definitions then add dryRun = true.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"}, dryRun = true)

public class RunYoursTest 
{
// This class will be empty 
}

Strict: if strict option is set to false then at execution time if cucumber encounters any undefined/pending steps then cucumber does not fail the execution and undefined steps are skipped and BUILD is SUCCESSFUL.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"}, strict = false)

public class RunYoursTest 
{
// This class will be empty 
}

and if Strict option is set to true then at execution time if cucumber encounters any undefined/pending steps then cucumber does fails the execution and undefined steps are marked as fail and BUILD is FAILURE. This is what the Console output looks like:

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"}, strict = true)

public class RunYoursTest 
{
// This class will be empty 
}

Monochrome: This option can either set as true or false (default value is false). If it is set as true, it means that the console output for the Cucumber test are much more readable. And if it is set as false, then the console output is not as readable as it should be. For practice just add the code ‘monochrome = true‘ in TestRunner class.

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"}, strict = true,
                 monochrome = true)

public class RunYoursTest 
{
// This class will be empty 
}

Features: Features Options helps Cucumber to locate the Feature file in the project folder structure.All we need to do is to specify the folder path and Cucumber will automatically find all the ‘.features‘ extension files in the folder.
It can be defined like:

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “Feature“
                )

public class RunYoursTest 
{
// This class will be empty 
}

Or if the feature file is in the deep folder structure-

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“
                )

public class RunYoursTest 
{
// This class will be empty 
}

Glue: It is almost the same think as Features Option but the only difference is that it helps Cucumber to locate theStep Definition file. Whenever Cucumber encounters a Step, it looks for a Step Definition inside all the files present in the folder mentioned in Glue Option.
It can be defined like-

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “Feature“
                  glue = “stepDefinition“
                )

public class RunYoursTest 
{
// This class will be empty 
}

Or if the Step Definition file is in the deep folder structure-

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“
                  glue = “src/test/stepDeinition“                  
                )

public class RunYoursTest 
{
// This class will be empty 
}

Snippet Style: Cucumber generates code snippets in Underscore style by default. If you want to change the format of cucumber snippets then you can set snippet type in your cucumber options. There are two types of snippets,

1- SnippetType.CAMELCASE
2- SnippetType.UNDERSCORE

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"}, monochrome = true
                 Snippets = SnippetType.CAMELCASE)

public class RunYoursTest 
{
// This class will be empty 
}

Running cucumber tests based on Tags

The tags can be used when specifying what tests to run through any of the running mechanism.
So, tags is just another parameter in the cucumber options annotation. We can also pass multiple tags as values separated by commas if we need so.

Tag expressions-

Running Scenarios with a Tag

Cucumber run scenarios with a particular tag.

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“,
                  tags ={“@Webdriver“},...  ) 

public class RunYoursTest 
{ 
// This class will be empty 
} 

Running Scenarios without Tag

Cucumber can exclude scenarios with a particular tag by inserting the tilde character before the tag.
For the following command will run all Scenarios without the SoapUI tag.

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“,
                  tags ={“~@SoapUI“},...  ) 

public class RunYoursTest 
{ 
// This class will be empty 
} 

Logical OR

Separate a list of tags by commas for a Logical OR tag expression.

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“,
                  tags ={“@SoapUI,@Functional"},...  ) 

public class RunYoursTest 
{ 
// This class will be empty 
}

Logical AND

Specifying multiple tag arguments creates a logical AND between each tag expression.

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“,
                  tags ={“@SoapUI","@Functional"},...  ) 

public class RunYoursTest 
{ 
// This class will be empty 
}

AND OR NOT

Specifying multiple tag arguments creates a logical AND between each tag expression.

@RunWith(Cucumber.class)
@CucumberOptions(
                  features = “src/test/features“,
                  tags ={“@SoapUI,@Functional","~@Regression"},...  ) 

public class RunYoursTest 
{ 
// This class will be empty 
}

So its all about @CucumberOptions. For more details please follow
Test Automation with Cucumber-JVM

Agile Behavior Driven Development and Integrated Testing with the Cucumber Framework

Now a days Behavior Driven Development is one of the powerful development style. When BDD integrate with agile then its become more dynamic.

Problem of testing also solved by BDD cucumber framework.

Test Driven Development (TDD)

tdd

In the TDD,
• First we write a test.
• Then we write code to make the test pass.
• Then we find the best possible design for what we have re-factoring (Relying on the existing tests to keep us from breaking things while we are at it)

BDD (Behavior Driven Development)

bdd1
• BDD is an improvement of the TDD practice.
• It’s Like the TDD flow but introducing the concept of human readable test that everybody can understand Key question of this improvement? Test cases can be understood by non developers and   testers including those stakeholders that doesn’t know anything about technology.
• Describe the behavior of your software in a very understandable way and normally what we want to test? The specifications of our software.

 BDD Flow

bddflow

-Everybody involved, giving their points of view.
-Early testing.
-Static testing, we can found inconsistencies.
-Devs can help in order to know if we have crazy ideas.
-Less rework.

Benefits of BDD
• Encourages Collaboration between Business Analysts, QA Engineers, Developers & Business Owners / Stakeholders.
• Driven by Business Value.
• Extends Test Driven Development (TDD) by utilizing natural language that non-technical stakeholders can understand.
• BDD Frameworks such as Cucumber or JBehave are an Enabler, acting a “bridge” between Business & Technical Language.
User Stories & Acceptance Criteria Defined in Feature Files with Business Language.
Developers Implement Acceptance Criteria.

Agile Core Principles

– Enough is enough do as much planning, analysis, and design as you need, but no more.
– Deliver stakeholder value everything you do should deliver value or increase your ability to do so.
– It’s a behavior everyone involved should have the same way of talking about the system and what it does.

Encourage Agile practices

• Individuals and interactions over processes and tools because with BDD we are going to have an agile documentation.
• Working software over comprehensive documentation because With BDD we are going to have less rework.
• Customer collaboration over contract negotiation because DEVs are going to have a clearer understanding of what they have to develop so we are going to have de working software earlier.
• Responding to change over following a plan because agile projects accommodate change systematically. The agile approaches to planning, working, and prioritization allow project teams to respond   quickly to change. The flexibility of agile approaches actually increases project stability, because change on agile projects is predictable and manageable.

Characteristics of BDD Agile Requirements


Requirements:
What the stakeholders require?
Requirements => User Stories

Functional Specification:
What the product will do to meet requirements?
Functional Specification => Examples, Acceptance Tests,
Given/When/Then

Technical Specification:
How the product will provide the functionality.
Technical Specification => Unit Tests, Functional Tests,
Integration Tests

Requirements


As an < User >
I want < some action >
So < Goal >

As an user
I want to log in into application
So I will be logged in

In order to < business goal >
As an < stakeholder >
I want < visible change in system >

Cucumber BDD Frameworks

Cucumber is designed for scenario implementation in Ruby, but after Cucumber JVM its support different implementations.

Cucumber-JVM (Pure Java)
Released April 2012
Java, Groovy, Clojure, Scala, Ioke, Jython, loke, Rhino (JavaScript) and Jruby

.NET: IronRuby
Cucumber Wrapper for IronRuby

This frame work is highly Flexible, with ability to integrate with any tool supported by underlying implementation, e.g.
• Web Automation (Webdriver / Waitr / Capybara)
• Various Languages (Java, .NET etc)
• Build Systems – Ant, Rake, Hudson, Jenkins etc
• Interface testing (example mozo poc)
• Various other Tools &amp, Scripting toolkits.

Basic .feature (User Story) Structure

Feature: [Title]

As a [Role]

I want [Some Action]

So that [Business Value]

Scenario: Title

Given [Context]

And [More Context]

When (I do) [Action]

And [Other Action]

Then (I should see) [Outcome]

And [More Outcomes]

– Description of Feature

– Stakeholder and/or User role

– Action to be taken by user.

– Business Value Provided

– Description of Scenario

– Preconditions of Scenario

– Some more preconditions

– Actions taken in Scenario

– Another action

–  Outcome Expected

– One or more Scenarios defined

Structure of a Feature File & Agile Workflow

Step 1: User Story / Requirement Elicitation & Elaboration
with Customer(s) or Business Owner – Feature file output

Step 2: User Story (Feature file) Elaboration & Validation
with QA

Step 3: Feature & Feature File Implementation by
Developers

Step 4: Testers Test Functionality
Step 5: Acceptance by Business Owner
Step 6: Repeat (In Event of Requirement Changes)

Conclusion

• BDD is a Mindset, Not a Set of Tools,Tools are immature.
• Requirements / Functionality Influenced by Consensus (general agreement).
• BDD Is Not a Replacement for Unit Testing.
• Need to be Mindful of Stakeholders When Wording Features & Scenarios.
• Make Sure Features are Broken Down into Sufficiently small “chunks”.

In my next post I will explain Test Automation with Cucumber-JVM.